@swarmcloud/hls 2.17.10 → 2.17.12
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/hls-proxy.js +1 -1
- package/hls.light.min.js +1 -1
- package/hls.min.js +1 -1
- package/hlsjs-p2p-engine.min.js +1 -1
- package/p2p-engine.es.min.js +1 -1
- package/p2p-engine.min.js +1 -1
- package/package.json +1 -1
- package/sw-p2p-engine.min.js +1 -1
package/hls.light.min.js
CHANGED
|
@@ -1 +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()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,s="object"==typeof Reflect?Reflect:null,i=s&&"function"==typeof s.apply?s.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)};t=s&&"function"==typeof s.ownKeys?s.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(s,i){function r(s){e.removeListener(t,n),i(s)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",r),s([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,s){"function"==typeof e.on&&p(e,"error",t,s)}(e,r,{once:!0})}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var 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?n.defaultMaxListeners:e._maxListeners}function h(e,t,s,i){var r,n,a,h;if(o(s),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),n=e._events),a=n[t]),void 0===a)a=n[t]=s,++e._eventsCount;else if("function"==typeof a?a=n[t]=i?[s,a]:[a,s]:i?a.unshift(s):a.push(s),(r=l(e))>0&&a.length>r&&!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 c(e,t,s){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},r=d.bind(i);return r.listener=s,i.wrapFn=r,r}function u(e,t,s){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?s?[r.listener||r]:[r]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(r):g(r,r.length)}function f(e){var t=this._events;if(void 0!==t){var s=t[e];if("function"==typeof s)return 1;if(void 0!==s)return s.length}return 0}function g(e,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=e[i];return s}function p(e,t,s,i){if("function"==typeof e.on)i.once?e.once(t,s):e.on(t,s);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(n){i.once&&e.removeEventListener(t,r),s(n)}))}}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),n.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var r="error"===e,n=this._events;if(void 0!==n)r=r&&void 0===n.error;else if(!r)return!1;if(r){var 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=n[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(s=0;s<h;++s)i(d[s],this,t)}return!0},n.prototype.addListener=function(e,t){return h(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return h(this,e,t,!0)},n.prototype.once=function(e,t){return o(t),this.on(e,c(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,c(this,e,t)),this},n.prototype.removeListener=function(e,t){var s,i,r,n,a;if(o(t),void 0===(i=this._events))return this;if(void 0===(s=i[e]))return this;if(s===t||s.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(r=-1,n=s.length-1;n>=0;n--)if(s[n]===t||s[n].listener===t){a=s[n].listener,r=n;break}if(r<0)return this;0===r?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,r),1===s.length&&(i[e]=s[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,s,i;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var r,n=Object.keys(s);for(i=0;i<n.length;++i)"removeListener"!==(r=n[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},n.prototype.listeners=function(e){return u(this,e,!0)},n.prototype.rawListeners=function(e){return u(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=a.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=a.normalizePath(r.path),a.buildURLFromParts(r)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(c)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=s.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=s.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()},424:(e,t)=>{"use strict";t.h=r;var s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=r.prototype,t}function r(e,t,s){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return n(e,t,s)}function n(e,t,s){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!r.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var s=0|d(e,t),n=i(s),a=n.write(e,t);a!==s&&(n=n.slice(0,a));return n}(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(v(e,ArrayBuffer)||e&&v(e.buffer,ArrayBuffer))return function(e,t,s){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(s||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,t):new Uint8Array(e,t,s);return i.__proto__=r.prototype,i}(e,t,s);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return r.from(n,t,s);var a=function(e){if(r.isBuffer(e)){var t=0|h(e.length),s=i(t);return 0===s.length||e.copy(s,0,0,t),s}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?i(0):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 r.from(e[Symbol.toPrimitive]("string"),t,s);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function 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),s=i(t),r=0;r<t;r+=1)s[r]=255&e[r];return s}function h(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function d(e,t){if(r.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||v(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var s=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===s)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":return m(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;default:if(n)return i?-1:m(e).length;t=(""+t).toLowerCase(),n=!0}}function c(e,t,s,i){s=Number(s)||0;const r=e.length-s;i?(i=Number(i))>r&&(i=r):i=r;const n=t.length;let a;for(i>n/2&&(i=n/2),a=0;a<i;++a){const i=parseInt(t.substr(2*a,2),16);if(y(i))return a;e[s+a]=i}return a}function u(e,t,s,i){return p(m(t,e.length-s),e,s,i)}function f(e,t,s,i){return p(function(e){const t=[];for(let s=0;s<e.length;++s)t.push(255&e.charCodeAt(s));return t}(t),e,s,i)}function g(e,t,s,i){return p(function(e,t){let s,i,r;const n=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)s=e.charCodeAt(a),i=s>>8,r=s%256,n.push(r),n.push(i);return n}(t,e.length-s),e,s,i)}function p(e,t,s,i){let r;for(r=0;r<i&&!(r+s>=t.length||r>=e.length);++r)t[r+s]=e[r];return r}function m(e,t){var s;t=t||1/0;for(var i=e.length,r=null,n=[],a=0;a<i;++a){if((s=e.charCodeAt(a))>55295&&s<57344){if(!r){if(s>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&n.push(239,191,189);continue}r=s;continue}if(s<56320){(t-=3)>-1&&n.push(239,191,189),r=s;continue}s=65536+(r-55296<<10|s-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,s<128){if((t-=1)<0)break;n.push(s)}else if(s<2048){if((t-=2)<0)break;n.push(s>>6|192,63&s|128)}else if(s<65536){if((t-=3)<0)break;n.push(s>>12|224,s>>6&63|128,63&s|128)}else{if(!(s<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(s>>18|240,s>>12&63|128,s>>6&63|128,63&s|128)}}return n}function v(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),r.from=function(e,t,s){return n(e,t,s)},r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,r.alloc=function(e,t,s){return function(e,t,s){return a(e),e<=0?i(e):void 0!==t?"string"==typeof s?i(e).fill(t,s):i(e).fill(t):i(e)}(e,t,s)},r.allocUnsafe=function(e){return o(e)},r.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==r.prototype},r.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return r.alloc(0);var s;if(void 0===t)for(t=0,s=0;s<e.length;++s)t+=e[s].length;var i=r.allocUnsafe(t),n=0;for(s=0;s<e.length;++s){var a=e[s];if(v(a,Uint8Array)&&(a=r.from(a)),!r.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,n),n+=a.length}return i},r.byteLength=d,r.prototype._isBuffer=!0,r.prototype.copy=function(e,t,s,i){if(!r.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<s&&(i=s),i===s)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-s&&(i=e.length-t+s);var n=i-s;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,s,i);else if(this===e&&s<t&&t<i)for(var a=n-1;a>=0;--a)e[a+t]=this[a+s];else Uint8Array.prototype.set.call(e,this.subarray(s,i),t);return n},r.prototype.write=function(e,t,s,i){if(void 0===t)i="utf8",s=this.length,t=0;else if(void 0===s&&"string"==typeof t)i=t,s=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(s)?(s>>>=0,void 0===i&&(i="utf8")):(i=s,s=void 0)}const r=this.length-t;if((void 0===s||s>r)&&(s=r),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return c(this,e,t,s);case"utf8":case"utf-8":return u(this,e,t,s);case"ascii":case"latin1":case"binary":return f(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,s);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}}},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var s={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return s.isAndroid()||s.isAndroidWebView()?t.ANDROID_WEB:s.isIOS()||s.isIpad()||s.isIOSWebView()?t.IOS_WEB:s.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!n(r("os "))&&!n(r("android[/ ]"))},isIOS:function(){return n(r("os "))},isIpad:function(){return i().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return n(r("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return s.isAndroid()||s.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=i();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=i();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return s.isAndroidWebView()||s.isIOSWebView()},device:t,getBrowser:function(){return s.isX5()?"X5":s.isAndroidWebView()?"Android-WebView":s.isIOSWebView()?"iOS-WebView":s.isChrome()?"Chrome":s.isFirefox()?"Firefox":s.isIpadSafari()?"iPad-Safari":s.isIOSSafari()?"iPhone-Safari":s.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function r(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=s}},t={};function s(i){var r=t[i];if(void 0!==r)return r.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,s),n.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";s.d(i,{default:()=>$l});const e={DC_SIGNAL:"SIGNAL",DC_SIGNAL_BATCH:"SIGNAL_BATCH",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_DISCONNECT:"DISCONNECT",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",BM_FATAL_ERROR:"BM_FATAL_ERROR",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PROGRESS:"SYN_PROGRESS",MEDIA_REBUFFER:"MEDIA_REBUFFER"},t={...e,SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_GET_MEDIA:"SW_GET_MEDIA",SW_DEBUG:"SW_DEBUG",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED"};var r=s(415),n=s.n(r),a=s(424),o=s(558),l=s.n(o);const h="__PROXY_IDENTIFIER__";const d={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},c=64e3;function u(){return!0}function f(e){return new URL(location.href).searchParams.get(e)}function g(e,t,s){const i=new URL(e);return i.searchParams.append(t,s),i.href}function p(){return Math.floor(Date.now()/1e3)}function m(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function v(e){return new Promise((t=>setTimeout(t,e)))}function y(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function E(e){const t=a.h.from(e),s=new a.h(e.byteLength);return t.copy(s),s}function S(){return location.protocol.startsWith("https")}function T(e,t,s){if(e.size<=t)return;const i=[...e.keys()];do{const t=i.shift();s&&s(e.get(t)),e.delete(t)}while(e.size>t)}function _(e,t){if(e.size<=t)return;const s=[...e.values()];do{e.delete(s.shift())}while(e.size>t)}function L(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function b(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const s=Number(t[0]),i=t[1]?Number(t[1]):-1;return{rangeStart:s,rangeEnd:i>=0?i+1:void 0}}function R(e){return e.split("?")[0]}function A(){let e=new Date,t=e.getHours(),s=e.getMinutes(),i=e.getSeconds(),r=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${r}`}function P(e){return e&&"function"==typeof e}function w(e,t,s,i,r,n){const{sn:a,seg_id:o,size:l,level:h}=s;e.sendPartialBuffer(s,i,{from:r,incompletes:n})&&(e.bitset.add(a,h,o,d.COMPLETE,l),i.length<s.attachments?function(e,t,s){e.addStreamListener(s,t.remotePeerId,((e,s,i,r,n)=>{i?t.sendMsgPieceAbort(r,s,!0):t.uploading&&t.send(r),n&&(t.uploading=!1)}))}(t,e,!!s.reverse):e.uploading=!1)}const I=e=>0===m(0,1)?[null,e]:[e,null];function D(e,t,s){return 1===e.length?t.length>=1&&s.length>=1?t[0].weight>s[0].weight?[t[0],e[0]]:[e[0],s[0]]:t.length>=1?[t[0],e[0]]:s.length>=1?[e[0],s[0]]:I(e[0]):[t.length>=1?t[0]:null,s.length>=1?s[0]:null]}function C(){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}}}async function k(e){if(crypto.subtle)try{const t=await crypto.subtle.digest("SHA-256",e),s=String.fromCharCode.apply(null,new Uint8Array(t));return btoa(s)}catch(e){}}function M(e,t,s){if(!t)return{message:e,stack:"",filename:s};let i="";if("string"==typeof t)i=t;else if(t.message)i=t.message;else if(t.error&&t.error.message)i=t.error.message;else if(t.reason&&t.reason.message)i=t.reason.message;else try{i=String(t)}catch(e){}let r="";return r=t.stack?t.stack:t.error&&t.error.stack?t.error.stack:t.reason&&t.reason.stack?t.reason.stack:"",{message:i.trim()||e,stack:r.trim()||JSON.stringify(t),filename:s}}class x{constructor(e,t){this.target=t,this.type=e}}class O extends x{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class F extends x{constructor(e=1e3,t="",s){super("close",s),this.code=e,this.reason=t,this.wasClean=!0}}const N=()=>{if("undefined"!=typeof WebSocket)return WebSocket},$={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class B{constructor(e,t,s={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=s,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return B.CONNECTING}get OPEN(){return B.OPEN}get CLOSING(){return B.CLOSING}get CLOSED(){return B.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?B.CLOSED:B.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws&&this._ws.readyState!==this.CLOSED&&this._ws.close(e,t)}reconnect(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()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._ws.send(e);else{const{maxEnqueuedMessages:t=$.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&this._messageQueue.push(e)}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const s of t)this._callEventListener(e,s);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=$.reconnectionDelayGrowFactor,minReconnectionDelay:t=$.minReconnectionDelay,maxReconnectionDelay:s=$.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=t*Math.pow(e,this._retryCount-1),i>s&&(i=s)),i}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=$.maxRetries,connectionTimeout:t=$.connectionTimeout,WebSocket:s=N()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(i=s)||!i||2!==i.CLOSING)throw Error("No valid WebSocket class provided");var i;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new s(e,this._protocols):new s(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new O(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new O(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new F(e,t,this))}catch(e){}}}_acceptOpen(){this._retryCount=0}_callEventListener(e,t){"handleEvent"in t?t.handleEvent(e):t(e)}_handleOpen(e){const{minUptime:t=$.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout((()=>this._acceptOpen()),t),this._ws.binaryType=this._binaryType,this._messageQueue.forEach((e=>this._ws.send(e))),this._messageQueue=[],this.onopen&&this.onopen(e),this._listeners.open.forEach((t=>this._callEventListener(e,t)))}_handleMessage(e){this.onmessage&&this.onmessage(e),this._listeners.message.forEach((t=>this._callEventListener(e,t)))}_handleError(e){this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._listeners.error.forEach((t=>this._callEventListener(e,t))),this._connect()}_handleClose(e){this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this._listeners.close.forEach((t=>this._callEventListener(e,t)))}_removeListeners(){this._ws&&(this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const U={debug:3,info:4,warn:5,error:6};class G{constructor(e,t,s,i){this.wsAddr=`${e}?app=${t}&id=${s}&v=${i}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:m(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new B(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const s=U[e];this._ws.send(JSON.stringify({records:[{level:s,text:`${A()}: ${t}`}]}))}sendBatch(e){const t=[];for(let s of e)t.push({level:U[s.levelKey],text:s.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const H={debug:0,info:1,warn:2,error:3,none:4};const V=class{constructor(e,t){this.logLevel=e,this.onlineDebug=!1,this.logCache=[],this.app=t;try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),(e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}})("SW_DEBUG")&&(this.logLevel="debug"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in H||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in H)this[e]=console[e];this._hookLogFunc(((e,t)=>{this.logUploader&&this.logUploader.send(e,t)}))}enableReport(e){this.reportUrl=e,this._hookLogFunc(((e,t)=>{this.reportUrl?(this.logCache.push({levelKey:e,message:`${A()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,s,i,r=5e3){this.reportUrl&&!this.reporter&&e&&(this.reporter=new G(this.reportUrl,`${t}(${this.app})`,s,i),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.logCache.unshift({levelKey:"info",message:e}),this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),r)}),{once:!0}))}_hookLogFunc(e){for(let t in H){const s=this[t];this[t]=i=>{e(t,i),s(i)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in H)H[e]<H[this.logLevel]?this[e]=u:this[e]=console[e]}get isDebugLevel(){return H[this.logLevel]<=2||this.onlineDebug}};let W;const q="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(W||(W=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),j=65536;function z(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class K extends(n()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||K.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},K.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=y(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void q((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var s;!t.address||t.address.endsWith(".local")?(s="Ignoring unsupported ICE candidate.",console.warn(s)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,q((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,q((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=j),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{e.debug=!0,this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>j}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=z(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=z(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((s=>{const i=[];s.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((s=>{if(this.destroyed)return;const i=[];s.result().forEach((e=>{const s={};e.names().forEach((t=>{s[t]=e.stat(t)})),s.id=e.id,s.type=e.type,s.timestamp=e.timestamp,i.push(t(s))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,s)=>{if(this.destroyed)return;t&&(s=[]);const i={},r={},n={};let a=!1;s.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(n[e.id]=e)}));const o=e=>{a=!0;let t=r[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let s=i[e.remoteCandidateId];s&&(s.ip||s.address)?(this.remoteAddress=s.ip||s.address,this.remotePort=Number(s.port)):s&&s.ipAddress?(this.remoteAddress=s.ipAddress,this.remotePort=Number(s.portNumber)):"string"==typeof e.googRemoteAddress&&(s=e.googRemoteAddress.split(":"),this.remoteAddress=s[0],this.remotePort=Number(s[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(s.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(n[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(n).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect");for(let e of this._pendingData)this.emit("data",e);this._pendingData=[]}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>j||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=a.h.from(t)),this._connected?this.emit("data",t):this._pendingData.length<10&&this._pendingData.push(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()}}K.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},K.channelConfig={};const Y=K;class X{constructor(e,t,s,i,r=0,n={}){this.sn=e,this.segId=t,this.data=s,this.fromPeerId=i,this.level=r,this.ext=n}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var Q=s(365),J=s.n(Q);class Z extends(n()){static get defaultPacketSize(){return c}static get VERSION(){return"8"}constructor(e,t,s,i,r,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=r,this.isInitiator=i,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.signalRejectCache="",this.assignPeerId(t,s),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=c,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.currentLost=0,this._currentSharedPeers=[],this.notFoundPeers=new Set,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.signalName="",this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,s){this.remotePeerId=s,this.channelId=this.isInitiator?`${t}-${s}`:`${s}-${t}`,s&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=p(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:s,signalName:i}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${s} signalName ${i}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:s,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,s,i){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${i} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:s,seg_id:i}))))}addStreamListener(e,t,s){this.streamListeners.push({handler:s,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const t=new Y({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let s=!0;(this.connected||this.notFatalClosed)&&(s=!1);let i=t.message;t.debug&&(i=`${i} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,s,i)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.byPeerSignal?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:s}=this;if("string"==typeof t){let i;try{i=JSON.parse(t)}catch(e){return void s.error(e)}if(!i)return void s.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(i);let r,n=i.event;switch(r=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,s.debug(`datachannel receive ${r} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(i.event,i),!i.sn)return;this.config.live||(i.sn<this.startSN&&(this.startSN=i.sn),i.sn>this.endSN&&(this.endSN=i.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=p(),this.timeReceivePiece=performance.now(),this.pieceMsg=i,this._prepareForBinary(i.attachments,i.seg_id,i.sn,i.size),this.emit(i.event,i);break;case e.DC_PIECE_CANCEL:s.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(i.event,i),this.sendMsgPieceAbort("transfer canceled",i.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(i.event,i);break;case e.DC_REQUEST:this._handleRequestMsg(i);break;case e.DC_PIECE_ACK:this._handlePieceAck(i.seg_id,i.size,i.miss);break;case e.DC_STATS:this._handleStats(i);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(i);break;case e.DC_METADATA:this._handleMetadata(i);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,i)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:s.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:s.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(i.event,i.fatal||!1);break;default:this.emit(i.event,i)}}else{if(!t)return void s.error("datachannel on data is undefined!");if(!this.downloading){const i=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return s.warn(i),void this.emit(e.DC_ERROR,!1,i)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,s)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const s=JSON.stringify(t);return s.length>c?(this.logger.error("string to send is too large"),!1):this.send(s,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const s=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,s)}return!1}sendMsgHave(t,s,i={}){const r=i.reverse||void 0;delete i.reverse,this.sendJson({event:r?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:s,...i})}sendPieceNotFound(t,s,i={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:s||void 0,sn:t,...i})}sendPeers(t){t.length>0&&this.sendJson({event:e.DC_PEERS,peers:t})}sendMsgStats(t,s,i={}){const r={event:e.DC_STATS,total_conns:t,shared_peers:s,...i};this.sendJson(r)}sendMsgPlaylist(t,s,i){const r=this.playlistMap.get(t);if(r&&r.seq>=i)return;const n={event:e.DC_PLAYLIST,url:t,data:s,seq:i};this.playlistMap.set(t,{data:s,seq:i}),this.sendJson(n)}sendMsgSignal(t,s,i){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:s,data:i})}sendMsgSignalReject(t,s,i,r=!1){const n=`${t}-${s}`;return this.signalRejectCache===n||(this.signalRejectCache=n,this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:s,reason:i,fatal:r}))}sendMetaData(t,s,i,r,n=!1,a=[]){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!J().isMobile(),mobile_net:n,channel:this.channel,version:"2.17.10",sequential:s,peers:i,region:r,shared_peers:a})}sendPartialBuffer(e,t,s={}){if(!this.sendMsgPiece(e,s))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const s={...e,ext:t};return this.sendJson(s)}sendBuffer(t,s,i,r={}){const n=r.reverse||void 0;if(delete r.reverse,!i)return void this.logger.error("sendBuffer payload is undefined!");let a=i.byteLength,o=0,l=0;a%this.packetSize==0?l=a/this.packetSize:(l=Math.floor(a/this.packetSize)+1,o=a%this.packetSize);let h={event:e.DC_PIECE,attachments:l,seg_id:s,sn:t,level:r.level,size:a,reverse:n};if(delete r.level,!this.sendMsgPiece(h,r))return;const d=function(e,t,s,i){let r=[];if(i){let n;for(let i=0;i<s-1;i++)n=e.slice(i*t,(i+1)*t),r.push(n);n=e.slice(e.byteLength-i,e.byteLength),r.push(n)}else{let i;for(let n=0;n<s;n++)i=e.slice(n*t,(n+1)*t),r.push(i)}return r}(i,this.packetSize,l,o);this._sendBufferArray(d,n),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}get byPeerSignal(){return!!this.intermediator&&!this.signalName}get useBackupSignal(){return"backup"===this.signalName}requestDataById(t,s,i=!1,r={}){const n={event:e.DC_REQUEST,seg_id:t,sn:s,...r,urgent:i};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),i?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(t,s=!1,i={}){const r={event:e.DC_REQUEST,sn:t,...i,urgent:s};this.downloading?(this.logger.info(`add req ${t} in queue`),s?this.sendReqQueue.unshift(r):this.sendReqQueue.push(r)):this._realRequestData(r)}_sendBufferArray(e,t=!1){const s=t?e.reverse():e;for(let e=0;e<s.length;e++)this.send(s[e])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0,this._loadedBytes=0}shouldWaitForRemain(e){return 0!==this.bufArrSize&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e,t){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,t&&this.incomingSignal.push(t),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:s}=t;s(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let s={event:e.DC_CLOSE,fatal:t};this.sendJson(s),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:s,reverse:i}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let r=i?this.remainAttachments+1:s-this.remainAttachments;const n=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,r,n,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:s}=e;s(this.bufSN,this.segId,!1,t,n)}if(n){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(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:s,seq:i}=e;this.playlistMap.set(t,{data:s,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const s=this.playlistMap.get(e);return s.seq<=t||s.seq>t+2?null:s}_handleMetadata(t){const{logger:s}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,s.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const i=t.channel;if(this.channel!==i){const t=`peer channel ${i} not matched!`;return s.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){s.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:i}=this.config;if(i&&t.token!==i)return void this.emit(e.DC_ERROR,!0,`super peer token ${t.token} not matched!`)}t.region&&(this.region=t.region);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,s.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,s.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),t.shared_peers&&(this._currentSharedPeers=[...t.shared_peers]),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=p();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos),e.shared_peers&&(this._currentSharedPeers=e.shared_peers,this.notFoundPeers=new Set([...this.notFoundPeers].filter((e=>this._currentSharedPeers.some((t=>t.id===e))))))}_handleRequestMsg(t){if(this.dataExchangeTs=p(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(t,s,i){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(s/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),i>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${i}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:s})}_prepareForBinary(e,t,s,i){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=s,this.expectedSize=i}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let s=a.h.concat(this.bufArr);const i=s.byteLength;if(i===this.expectedSize){let t=s.buffer;const i=new X(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,i,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${i}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,s=performance.now()-this.timeSendRequest;if((e||!(s<1e3))&&(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>=3&&!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`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}get currentSharedPeers(){return[...this._currentSharedPeers].filter((e=>!this.notFoundPeers.has(e.id)))}clearCurrentSharedPeers(){this._currentSharedPeers=[]}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t,s,i=!1){const r=this.datasToSend.length;if(!i&&!this.uploading&&0===r)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(s,this.bytesUploaded,0),this.bytesUploaded=0;const n={event:e.DC_PIECE_ABORT,reason:`${t}, remains ${r}`};return this.sendJson(n)}loadedBytes(){return this._loadedBytes}currentLoadSpeed(){return 0===this.timeReceivePiece?0:this.loadedBytes()/(performance.now()-this.timeReceivePiece)}minRequiredSpeed(e){return(this.pieceMsg.size-this.loadedBytes())/e}}const ee=Z,te={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",RadiantMP:"rmp",bitmovin:"bitmovin"};const se={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class ie extends(n()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===f("_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");this.segmentLoadCount=0,this.rangeTested=!1,this.trackerTried=!1,this.playerName=function(){let e;for(let t in te)if(self[t]){e=te[t];break}return e}(),this.netType=J().getNetType()||"wifi"}resumeTracker(){this.tracker&&!this.trackerTried&&!this.tracker.connected&&this.config.p2pEnabled&&(this.tracker.resumeP2P(),this.trackerTried=!0)}onTrackerResume(e){if(e.report_url){const{logger:t}=this;t.enableReport(e.report_url);const s=(e,s)=>{t&&t.report(JSON.stringify(e,null,2),s,this.peerId,"2.17.10")};window.addEventListener("error",(e=>{s(M(e.message,e.error,e.filename),"globalJSError")}),{once:!0}),window.addEventListener("unhandledrejection",(e=>{s(M("",e.reason),"unhandledRejectionError")}),{once:!0})}}startRangeRequestTimer(){const{config:e,logger:t}=this;let s=0;const i=()=>{this.curTsUri&&function(e,t,s,i=2e3,r=!1){const n=new XMLHttpRequest;let a=e;return r&&(a=g(e,h,!0)),t=t||"bytes=0-0",new Promise(((r,o)=>{n.open("GET",a,!0),n.responseType="arraybuffer",n.timeout=i,n.onreadystatechange=e=>{if(4===n.readyState){const e=n.status;206===e?r(n.response):o(`status ${e} url ${a} range ${t}`)}},n.onerror=e=>{o("request error")},n.ontimeout=e=>{o("timeout")},n.setRequestHeader("Range",t),s&&s(n,e),n.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((r=>{e.httpRangeSupported=!1,t&&t.warn(r),s<3&&(this.rangeRequestTimer=setTimeout(i,6e4)),s++})).finally((()=>{t&&t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(i,0)}initLogger(){const{config:e}=this,t=new V(e.logLevel,e.token||location.hostname);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this;if(!e.scheduler)return;const t=e.scheduler.peersNum;return t>0&&e.maxConnsActive-t>0?e.maxConnsActive-t:void 0}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 P(t)?(s,i)=>`${e}-${t(s,i)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,s=`wss://${self.atob(function(e){let t="c2lnbmFsY2xvdWQuc3dhcm1jbG91ZC5vcmc=";switch(e){case"hk":t="c2lnbmFsLnN3YXJtY2xvdWQub3Jn";break;case"us":t="b3BlbnNpZ25hbC5zd2FybWNsb3VkLm9yZw==";break;case"cn":t="Z3ouc3dhcm1jbG91ZC5uZXQ="}return t}(t.trackerZone))}`;t.signalConfig&&(t.wsSignalerAddr=t.signalConfig);const{wsSignalerAddr:i}=t;if(i){let r;"object"==typeof i?(i.main||(i.main=s),r=i.main):"string"==typeof i&&(r=i,t.wsSignalerAddr={main:r}),r===s&&(r=void 0),r&&!t.wsSignalerAddr.backup&&(e=l().parseURL(r).netLoc.substring(2))}else t.wsSignalerAddr={main:s,byDefault:!0};return e}get commonBrowserInfo(){const e=J().getPlatform(),{main:t,backup:s,byDefault:i}=this.config.wsSignalerAddr||{};return{signal:t,custom_signal:!i||void 0,signal2:s,device:e,netType:this.netType,player:this.playerName}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",s=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,s)};e?self.removeEventListener(t,s):self.addEventListener(t,s)}destroy(){clearTimeout(this.rangeRequestTimer),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 ie.version}static isSupported(){const e=y();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,s){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${s}`);let i=4;return t<=2?i=1.5:t<=3?i=2:t<=4?i=2.5:t<=5?i=3:t<=6&&(i=3.5),i}emitEvent(e,...t){this.emit(e,...t);const s=se[e];s&&P(this.config[s])&&this.config[s](...t)}}ie.version="2.17.10",ie.protocolVersion=ee.VERSION;const re=ie;function ne(){if(!function(){if("object"==typeof self)return self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}())return!1;const e=self.SourceBuffer||self.WebKitSourceBuffer;return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function ae(e,t){let s;if(e&&("string"==typeof e?(s=document.querySelector(e),oe(s)||(s=function(e){const t=document.getElementById(e);if(oe(t))return t;if(!t)return null;const s=t.getElementsByTagName("*");for(let e=0;e<s.length;e++)if(oe(s[e]))return s[e];return null}(e))):e instanceof HTMLMediaElement&&(s=e)),!s){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?s=e[0]:(t&&(s=e.find((e=>e.src===t))),s||(s=e.find((e=>e.currentTime>0))))}return s}function oe(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function le(e,t,s,i=0,r=0){const n=c;let a=i,o=r||s-1;const l=Math.floor(s/n),h=s%n>0?l+1:l;if(e>=0&&(a+=(e+1)*n),t>=0&&t<h){o-=s%n+(h-t-1)*n}return{rangeStart:a,rangeEnd:o+1}}function he(e,t){return`${e}-${t}`}function de(e,t,s,i){let r=s.split("?")[0];return r.startsWith("http")&&(r=r.split("://")[1]),i?`${r}|${i}`:`${r}`}function ce(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}let ue={wsMaxRetries:10,p2pEnabled:!0,signalCompact:!0,wifiOnly:!1,memoryCacheLimit:{pc:419430400,mobile:104857600},dcDownloadTimeout:25,logLevel:"error",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:3,trickleICE:!0,announceLocation:"eu",trackerZone:void 0,ICEPreflight:!0,useDiskCache:!0,startFromSegmentOffset:3,getStats:function(e,t,s){},getPeerId:function(e){},getPeersInfo:function(e){}};const fe={...ue,httpLoadTime:0,sharePlaylist:!1,useHttpRange:!0,hlsjsInstance:null,proxyOnly:!1,proxyFirst:!1,p2pBlackList:["vtt","webvtt","key"],live:!0,swFile:"./sw.js",swScope:"./",swAutoRegister:!0,mediaElem:void 0,httpStreamEnabled:!0,diskCacheLimit:{pc:1572864e3,mobile:1048576e3},strictSegmentId:!1,prefetchOnly:!1},ge=1e3;function pe(e){const t=new Promise(((t,s)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>s(e.error)})),s=(i=ge,r="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(r)}),i))));var i,r;return Promise.race([t,s])}const me={};async function ve(e,t,s=!0){const i=me[e]||{};i.promise||(i.promise=new Promise((e=>i.resolve=e)),me[e]=i,Ee(e,t,i.resolve,s));const r=await i.promise;return delete i.promise,r}const ye={};async function Ee(e,t,s,i){if(!ye[e]){const i=indexedDB.open(e);return i.onupgradeneeded=()=>{const e=i.result;t.forEach((t=>{e.createObjectStore(t)}))},void s(ye[e]=await pe(i))}if(i)try{t.forEach((t=>{ye[e].transaction(t)})),s(ye[e])}catch(r){console.error(`Could not open a transaction on "${e}" due to ${r.name} (${r.message}). Trying to reopen the connection...`),delete ye[e],Ee(e,t,s,i)}else s(ye[e])}let Se;function Te(){return Se||(Se=createStore("keyval-store","keyval")),Se}function _e(e,t=Te()){return t("readonly",(t=>pe(t.get(e))))}function Le(e,t,s=Te()){return s("readwrite",(s=>(s.put(t,e),pe(s.transaction))))}function be(e,t=Te()){return t("readwrite",(t=>(t.delete(e),pe(t.transaction))))}function Re(e=Te()){return e("readwrite",(e=>(e.clear(),pe(e.transaction))))}function Ae(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},pe(e.transaction)}const Pe="size";class we extends(n()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info(`use ${this.name}`),this.engine=e,this.channel=e.channel;const s=e.browserInfo.device;this.isPC=s===J().device.PC_WEB||s===J().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.countErrors=0,this.isCleared=!0,this.destroyed=!1}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t<this.maxBufSize&&(this.maxBufSize=t-104857600)}return new Promise((async(e,t)=>{if(this.isPC&&this.maxBufSize<419430400||!this.isPC&&this.maxBufSize<104857600)return void t("disk storage not enough");const s=this.stores;let i;try{i=function(e,t){let s=ve(e,t);return t.map((i=>(r,n)=>s.then((a=>{try{const e=a.transaction(i,r).objectStore(i);return n(e)}catch(a){s=ve(e,t),s.then((e=>n(e.transaction(i,r).objectStore(i))))}}))))}(this.channel,s)}catch(e){return void t(e)}this._createStores(i),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return Le(Pe,0,this.metaStore)}currBufSize(){return new Promise((async(t,s)=>{try{const i=await _e(Pe,this.metaStore);if(isNaN(i))return this.engine.emit(e.BM_FATAL_ERROR),void s("size is NaN");t(i)}catch(e){s(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:s}=this;if(L(t.data))return new Promise((i=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,i()})).catch((e=>{this._handleFataError(),e&&(s.warn(`putSeg ${e}`),("QuotaExceededError"===e.name||e.inner&&"QuotaExceededError"===e.inner.name)&&this.currBufSize().then((e=>{this._trimDisk(e,!0)})).catch((e=>{this.logger.error(`trimDisk ${e}`)}))),i()}))}));s.error(`putSeg ${t.segId} is not buffer`)}_handleFataError(){this.countErrors++,this.countErrors>=3&&(this.engine.emit(e.BM_FATAL_ERROR),this.countErrors=0)}_decreaseBufSize(e){this.currBufSize().then((t=>{t&&Le(Pe,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{Le(Pe,t+e,this.metaStore),this._trimDisk(t+e)})).catch((e=>{this.logger.warn(`increaseBufSize ${e}`)}))}clear(e=!1){if(!this.isCleared){this.logger.warn("clear segment store");try{this._clearDisk(e)}catch(e){}this.isCleared=!0}}_clearDisk(e){Re(this.segmentsStore),e?this._initMetaStore():Re(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}static toSegment(e){const t=new X(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}}const Ie=we;const De=class extends Ie{constructor(e,t){super(e,t),this.loadingSN=-1,this.stores=["segments","id2Sn","metadata"]}_createStores(e){this.segmentsStore=e[0],this.id2SnStore=e[1],this.metaStore=e[2]}async hasSegOfId(e){if(!e)return Promise.resolve(!1);let t;try{t=await _e(e,this.id2SnStore)}catch(e){return Promise.resolve(!1)}return new Promise((s=>{void 0!==t?_e(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?s(!0):s(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),s(!1)})):s(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let s;try{s=await _e(e,this.id2SnStore)}catch(e){return null}return new Promise((i=>{void 0!==s?_e(s,this.segmentsStore).then((s=>{if(this.countErrors=0,s&&s.length>0){const r=s.find((t=>t.segId===e));if(!r)return void i(null);if(!L(r.data))return t.error(`getSegById ${r.sn} is not buffer`),void i(null);i(Ie.toSegment(r))}else i(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),i(null)})):i(null)}))}getSegIdBySN(e){return new Promise((t=>{_e(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.warn(`getSegIdBySN ${e}`),t(null)}))}))}_addSeg(e){const{segId:t,sn:s,size:i}=e;return Le(t,s,this.id2SnStore),new Promise(((r,n)=>{_e(s,this.segmentsStore).then((async a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(await this._segmentToCache(e)),Le(s,a,this.segmentsStore).then((()=>{this._increaseBufSize(i),r(e)})).catch((e=>{n(e)}))):r(e):Le(s,[await this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(i),r(e)})).catch((e=>{n(e)}))})).catch((e=>{n(e)}))}))}async _trimDisk(t,s=!1){if(this.isCleared||this.destroyed)return;let i=this.maxBufSize;const{logger:r}=this;s&&(i=t-104857600,i<0&&(i=0)),t<i||(r.warn(`_trimDisk currentSize ${t} upBound ${i}`),function(e=Te()){return e("readonly",(e=>{if(e.getAllKeys)return pe(e.getAllKeys());const t=[];return Ae(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async s=>{const n=s.sort(((e,t)=>e-t));let a=0;do{if(a++>10){r.warn("too much loops in SegmentStore");break}const s=n.shift();if(void 0===s){r.warn("lastSN not found");continue}if(s>=this.loadingSN){r.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const i=n[0],o=await _e(s,this.segmentsStore);if(!o){r.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),be(s,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((t=>{be(t.segId,this.id2SnStore),r.info(`pop seg ${t.segId} size ${t.data.byteLength}`),this.emit(e.BM_LOST,{sn:s,segId:t.segId,next:i,level:t.level})})),t-=l,r.info(`pop sn ${s} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=i)})))}async _segmentToCache(e){const{ext:t={}}=e;let s=t.hash;s||(s=await k(e.data));const i={data:e.data,level:e.level,segId:e.segId,sn:e.sn,fromPeerId:e.fromPeerId,ext:{}};return s&&(i.ext.hash=s),i}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}Re(this.id2SnStore).catch((e=>{}))}};class Ce extends(n()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const s=e.browserInfo.device;if(this.maxBufSize=s===J().device.PC_WEB||s===J().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,this.isLive=t.live,this.isLive)this.maxBufSize=47185920;else{if(0===this.maxBufSize)throw new Error("cannot use SegmentCache");const e=function(){const{memory:e}=performance;return e?e.jsHeapSizeLimit-e.usedJSHeapSize:-1}();e>=0&&e<this.maxBufSize&&(this.maxBufSize=e-31457280)}this._segPool=new Map,this._currBufSize=0,this.overflowed=!1,this.isCleared=!0,this.destroyed=!1}get currBufSize(){return this._currBufSize}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}async putSeg(e){this.destroyed||(this.isCleared=!1,this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),L(e.data)?this._addSeg(e):this.logger.error(`putSeg ${e.segId} is not buffer`))}clear(){this.isCleared||(this.logger.warn("clear segment cache"),this._segPool.clear(),this._currBufSize=0,this.isCleared=!0,this.overflowed=!1)}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const ke=Ce;const Me=class extends ke{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,s)=>{const i=this.id2Sn.get(e);this._segPool.has(i)?t(this._segPool.get(i).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((s,i)=>{if(!this._segPool.has(t))return void s(null);const r=this._segPool.get(t).find((t=>t.segId===e));s(r||null)}))}getSegIdBySN(e){return new Promise(((t,s)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}async _addSeg(t){const{logger:s}=this,{segId:i,sn:r,size:n,ext:a={}}=t;if(this.id2Sn.set(i,r),this._segPool.has(r)){this._segPool.get(r).push(t)}else this._segPool.set(r,[t]);this._currBufSize+=parseInt(n);const o=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSize<this.maxBufSize||o<=5)return;let l=Array.from(this._segPool.keys());this.isLive||(l=l.sort(((e,t)=>e-t)));let h=0;do{if(h++>10){s.error("too much loops in SegmentCache");break}const t=l.shift();if(void 0===t){s.error("lastSN not found");continue}const i=l[0],r=this._segPool.get(t);if(!r){s.error("lastSeg not found");continue}let n=0;r.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(t),r.forEach((s=>{this.id2Sn.delete(s.segId),this.emit(e.BM_LOST,{sn:t,segId:s.segId,next:i,level:s.level})})),s.info(`pop sn ${t} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){super.clear(),this.id2Sn.clear()}};function xe(e,t){for(const s in t)Object.defineProperty(e,s,{value:t[s],enumerable:!0,configurable:!0});return e}const Oe=function(e,t,s){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");s||(s={}),"object"==typeof t&&(s=t,t=void 0),null!=t&&(s.code=t);try{return xe(e,s)}catch(t){s.message=e.message,s.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),xe(new i,s)}};class Fe{constructor(){this.p2p=0,this.share=0,this.http=0}recordP2p(e){this.p2p+=e}recordShare(e){this.share+=e}recordHttp(e){this.http+=e}resetTraffic(){this.p2p=0,this.share=0,this.http=0}get healthRatio(){if(0===this.http)return 1e3;let e=Math.round((this.p2p+this.share)/this.http*100);return e<=0&&(e=1),e}}const Ne="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class $e{constructor(e=new Uint8Array(16)){this.buf=ArrayBuffer.isView(e)?e:new Uint8Array(e),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(e,t,s=this.length){for(;this.pos<s;){const s=this.readVarint(),i=s>>3,r=this.pos;this.type=7&s,e(i,t,this),this.pos===r&&this.skip(s)}return t}readDouble(){const e=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,e}readVarint(e){const t=this.buf;let s,i;return i=t[this.pos++],s=127&i,i<128?s:(i=t[this.pos++],s|=(127&i)<<7,i<128?s:(i=t[this.pos++],s|=(127&i)<<14,i<128?s:(i=t[this.pos++],s|=(127&i)<<21,i<128?s:(i=t[this.pos],s|=(15&i)<<28,function(e,t,s){const i=s.buf;let r,n;if(n=i[s.pos++],r=(112&n)>>4,n<128)return Be(e,r,t);if(n=i[s.pos++],r|=(127&n)<<3,n<128)return Be(e,r,t);if(n=i[s.pos++],r|=(127&n)<<10,n<128)return Be(e,r,t);if(n=i[s.pos++],r|=(127&n)<<17,n<128)return Be(e,r,t);if(n=i[s.pos++],r|=(127&n)<<24,n<128)return Be(e,r,t);if(n=i[s.pos++],r|=(1&n)<<31,n<128)return Be(e,r,t);throw new Error("Expected varint not more than 10 bytes")}(s,e,this)))))}readBoolean(){return Boolean(this.readVarint())}readString(){const e=this.readVarint()+this.pos,t=this.pos;return this.pos=e,e-t>=12&&Ne?Ne.decode(this.buf.subarray(t,e)):function(e,t,s){let i="",r=t;for(;r<s;){const t=e[r];let n,a,o,l=null,h=t>239?4:t>223?3:t>191?2:1;if(r+h>s)break;1===h?t<128&&(l=t):2===h?(n=e[r+1],128==(192&n)&&(l=(31&t)<<6|63&n,l<=127&&(l=null))):3===h?(n=e[r+1],a=e[r+2],128==(192&n)&&128==(192&a)&&(l=(15&t)<<12|(63&n)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===h&&(n=e[r+1],a=e[r+2],o=e[r+3],128==(192&n)&&128==(192&a)&&128==(192&o)&&(l=(15&t)<<18|(63&n)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,h=1):l>65535&&(l-=65536,i+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),i+=String.fromCharCode(l),r+=h}return i}(this.buf,t,e)}skip(e){const t=7&e;if(0===t)for(;this.buf[this.pos++]>127;);else if(2===t)this.pos=this.readVarint()+this.pos;else if(5===t)this.pos+=4;else{if(1!==t)throw new Error(`Unimplemented type: ${t}`);this.pos+=8}}writeTag(e,t){this.writeVarint(e<<3|t)}realloc(e){let t=this.length||16;for(;t<this.pos+e;)t*=2;if(t!==this.length){const e=new Uint8Array(t);e.set(this.buf),this.buf=e,this.dataView=new DataView(e.buffer),this.length=t}}finish(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)}writeVarint(e){(e=+e||0)>268435455||e<0?function(e,t){let s,i;e>=0?(s=e%4294967296|0,i=e/4294967296|0):(s=~(-e%4294967296),i=~(-e/4294967296),4294967295^s?s=s+1|0:(s=0,i=i+1|0));if(e>=0x10000000000000000||e<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");t.realloc(10),function(e,t,s){s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos]=127&e}(s,0,t),function(e,t){const s=(7&e)<<4;if(t.buf[t.pos++]|=s|((e>>>=3)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;t.buf[t.pos++]=127&e}(i,t)}(e,this):(this.realloc(4),this.buf[this.pos++]=127&e|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=e>>>7&127))))}writeBoolean(e){this.writeVarint(+e)}writeString(e){e=String(e),this.realloc(4*e.length),this.pos++;const t=this.pos;this.pos=function(e,t,s){for(let i,r,n=0;n<t.length;n++){if(i=t.charCodeAt(n),i>55295&&i<57344){if(!r){i>56319||n+1===t.length?(e[s++]=239,e[s++]=191,e[s++]=189):r=i;continue}if(i<56320){e[s++]=239,e[s++]=191,e[s++]=189,r=i;continue}i=r-55296<<10|i-56320|65536,r=null}else r&&(e[s++]=239,e[s++]=191,e[s++]=189,r=null);i<128?e[s++]=i:(i<2048?e[s++]=i>>6|192:(i<65536?e[s++]=i>>12|224:(e[s++]=i>>18|240,e[s++]=i>>12&63|128),e[s++]=i>>6&63|128),e[s++]=63&i|128)}return s}(this.buf,e,this.pos);const s=this.pos-t;s>=128&&function(e,t,s){const i=t<=16383?1:t<=2097151?2:t<=268435455?3:Math.floor(Math.log(t)/(7*Math.LN2));s.realloc(i);for(let t=s.pos-1;t>=e;t--)s.buf[t+i]=s.buf[t]}(t,s,this),this.pos=t-1,this.writeVarint(s),this.pos+=s}writeDouble(e){this.realloc(8),this.dataView.setFloat64(this.pos,e,!0),this.pos+=8}writeVarintField(e,t){this.writeTag(e,0),this.writeVarint(t)}writeStringField(e,t){this.writeTag(e,2),this.writeString(t)}writeDoubleField(e,t){this.writeTag(e,1),this.writeDouble(t)}writeBooleanField(e,t){this.writeVarintField(e,+t)}}function Be(e,t,s){return s?4294967296*t+(e>>>0):4294967296*(t>>>0)+(e>>>0)}function Ue(e,t){return e.readFields(Ge,{},t)}function Ge(e,t,s){1===e?t.id=s.readString():2===e?t.ip=s.readString():3===e?t.country=s.readString():4===e?t.isp=s.readString():6===e?t.conns=s.readVarint(!0):7===e?t.fail_rate=s.readDouble():8===e?t.mobile=s.readBoolean():9===e?t.source=s.readString():10===e?t.score=s.readDouble():11===e?t.lon=s.readDouble():12===e?t.lat=s.readDouble():13===e?t.platform=s.readString():14===e&&(t.super=s.readBoolean())}function He(e,t){e.channel&&t.writeStringField(1,e.channel),e.device&&t.writeStringField(2,e.device),e.live&&t.writeBooleanField(3,e.live),e.tag&&t.writeStringField(4,e.tag),e.ts&&t.writeVarintField(5,e.ts),e.type&&t.writeStringField(6,e.type),e.version&&t.writeStringField(7,e.version),e.netType&&t.writeStringField(8,e.netType),e.app&&t.writeStringField(9,e.app),e.announce&&t.writeStringField(10,e.announce),e.nat&&t.writeStringField(12,e.nat),e.token&&t.writeStringField(14,e.token),e.k&&t.writeStringField(15,e.k),e.abr&&t.writeBooleanField(16,e.abr),e.pos&&t.writeVarintField(25,e.pos),e.signal&&t.writeStringField(26,e.signal),e.signal2&&t.writeStringField(27,e.signal2),e.custom_signal&&t.writeBooleanField(28,e.custom_signal)}function Ve(e,t,s){1===e?t.id=s.readString():2===e?t.ip=s.readString():3===e?t.country=s.readString():4===e?t.asn=s.readString():8===e?t.total=s.readVarint(!0):9===e?t.score=s.readString():11===e?t.report_interval=s.readVarint(!0):12===e?t.peers.push(Ue(s,s.readVarint()+s.pos)):13===e?t.info=s.readString():14===e?t.warn=s.readString():15===e?t.rejected=s.readBoolean():16===e?t.min_conns=s.readVarint(!0):17===e?t.wifi_only=s.readBoolean():18===e?t.signal=s.readString():19===e?t.signal2=s.readString():20===e?t.stun.push(s.readString()):21===e?t.log_url=s.readString():22===e?t.report_url=s.readString():23===e?t.debug=s.readBoolean():24===e?t.fuse_rate=s.readVarint(!0):25===e?t.token=s.readString():26===e?t.token2=s.readString():27===e?t.slogan=s.readBoolean():30===e&&(t.overload=s.readBoolean())}function We(e,t){if(e.exclusions)for(const s of e.exclusions)t.writeStringField(1,s);e.level&&t.writeStringField(2,e.level),e.num_want&&t.writeVarintField(3,e.num_want),e.urgent&&t.writeBooleanField(6,e.urgent),e.ratio&&t.writeVarintField(7,e.ratio)}function qe(e,t,s){1===e?t.peers.push(Ue(s,s.readVarint()+s.pos)):2===e?t.total=s.readVarint(!0):3===e?t.score=s.readString():4===e&&(t.pos=s.readString())}function je(e,t){e.p2p&&t.writeVarintField(1,e.p2p),e.http&&t.writeVarintField(2,e.http),e.share&&t.writeVarintField(3,e.share),e.conns&&t.writeVarintField(4,e.conns),e.totalConns&&t.writeVarintField(5,e.totalConns),e.failConns&&t.writeVarintField(6,e.failConns),e.rebuffers&&t.writeVarintField(7,e.rebuffers),e.requests&&t.writeVarintField(8,e.requests),e.pos&&t.writeVarintField(10,e.pos),e.level&&t.writeStringField(11,e.level),e.off&&t.writeBooleanField(12,e.off)}function ze(e,t,s){1===e?t.code=s.readVarint(!0):2===e&&(t.msg=s.readString())}function Ke(e,t,s){1===e?t.ret=s.readVarint(!0):2===e?(t.channel_response=function(e,t){return e.readFields(Ve,{peers:[],stun:[]},t)}(s,s.readVarint()+s.pos),t.data="channel_response"):3===e?(t.peers_response=function(e,t){return e.readFields(qe,{peers:[]},t)}(s,s.readVarint()+s.pos),t.data="peers_response"):4===e&&(t.err_data=function(e,t){return e.readFields(ze,{code:0},t)}(s,s.readVarint()+s.pos),t.data="err_data")}const Ye="TRACKER_EXPT",Xe="uY2R",Qe="LmNv",Je="uYnll",Ze="bQ==",et="Z3o",tt=Symbol("httpDownloaded"),st=Symbol("p2pDownloaded"),it=Symbol("p2pUploaded");class rt extends(n()){constructor(e,t,s,i,r){let n;super(),this.config=e.config;let a=this.config.announceLocation;switch(this.config.trackerZone&&(a=this.config.trackerZone),a){case"hk":n="aGsubWVzaGlmeS5jbG91ZA==";break;case"us":n="dXMubWVzaGlmeS5jbG91ZA==";break;case"cn":n=et+Xe+Je+Qe+Ze;break;default:n="ZXUubWVzaGlmeS5jbG91ZA=="}this.engine=e,this.key=t||void 0,Array.isArray(i)&&(i=i[Math.floor(Math.random()*i.length)]),this.baseUrl=i||`https://${self.atob(n)}/v1`,this.channelId=self.btoa(s),this.timestamp=p(),this.health=new Fe;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),this.native=!(!r.bundle||!window.electron&&!navigator.userAgent.toLowerCase().includes("electron")),this.announceInfo={...r,channel:this.channelId,ts:this.timestamp,version:"2.17.10",announce:this.announce,k:lt(this.key)},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.statsRequesting=!1,this.statsLimited=!1,this.reportInterval=30,this.bigValueReported=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[tt]=0,this[st]=0,this[it]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,s)=>{ht(this.announceURL,this._requestHeader,this.announceInfo,He,((e,t)=>{if(!e){const e=t>=500&&t<600;s(Oe(new Error(`server response code is ${t}`),Ye,{retry:e}))}}),(e=>{if(!this.engine||!e)return;const i=e.data;if(i){if(i.slogan&&console.log(`%cLet the browsers become your unlimitedly scalable CDN!\n%cGet Free Trial \u{1f449} ${self.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldA==")} ${self.atob("aHR0cHM6Ly9zd2FybS1jbG91ZC5naXRodWIuaW8vaG9tZQ==")}`,"color: dodgerblue; padding:20px 0; font-size: xx-large","font-size: medium; padding-bottom:15px"),i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),-1===e.ret){const{code:t,msg:i}=e.data;s(Oe(new Error(i),Ye,{retry:t>=5e3}))}if((!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval){if(this.peerId=this.id=i.id,i.report_interval<20&&(i.report_interval=20),this.reportInterval=i.report_interval,this.btStats(),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,!this.announceInfo.asn&&i.asn){const{country:e,asn:t}=i;this.engine.emitEvent("geographicInfo",{country:e,asn:t}),this.announceInfo={...this.announceInfo,country:e,asn:t}}this.engine.emitEvent("serverConnected",!0),t(i)}else this.engine&&(this.engine.p2pEnabled=!1)}}),(t=>{e.error(`announce error ${t}`);const i=t.code||Ye,r=!t.code||t.retry;s(Oe(t,i,{retry:r}))}))}))}btStats(){clearInterval(this.heartbeater),this.heartbeater=setInterval((()=>{this.postStats()}),1e3*this.reportInterval)}postStatsWithBeacon(){if(this.offline)return;this.engine.emitEvent("serverConnected",!1),this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),this.statsURL&&navigator.sendBeacon&&navigator.sendBeacon(this.statsURL,dt(e,je))}postStats(t=!1){const{logger:s}=this.engine;if(this.statsRequesting)return!1;if(t){if(this.statsLimited)return!1;this.btStats()}return this.statsLimited=t,this.statsRequesting=!0,ht(this.statsURL,{},this._makeStatsBody(),je,(()=>{this.statsRequesting=!1,this.reportFails=0}),(t=>{if(t||(t={ret:0,data:{}}),-1===t.ret)clearInterval(this.heartbeater),s.error(`${t.data.msg} code ${t.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:s=0,failConns:i=0,rebuffers:r=0,requests:n=0}=this.lastStats||{};this[tt]>=e&&(this[tt]-=e),this[st]>=t&&(this[st]-=t),this[it]>=s&&(this[it]-=s),this.failConns>=i&&(this.failConns-=i),this.errsBufStalled>=r&&(this.errsBufStalled-=r),this.mediaRequests>=n&&(this.mediaRequests-=n)}this.bigValueReported&&(this[st]=0,this.bigValueReported=!1)}),(t=>{s.error(`stats error ${t}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&(clearInterval(this.heartbeater),this.engine.emit(e.RESTART_P2P))})),!0}btGetPeers(e,t=!1){const{logger:s}=this.engine;let i={exclusions:e,ratio:this.health.healthRatio,urgent:t||void 0},r={};return this.engine.getExtraForPeersRequest&&(r=this.engine.getExtraForPeersRequest()),i=Object.assign({},i,r),new Promise(((e,t)=>{this.reportFails>=3?t(new Error("reportFails >= 3")):ht(this.getPeersURL,this._requestHeader,i,We,null,(s=>{-1===s.ret?t(s.data.msg):e(s.data)}),(e=>{s.error(`getPeers error ${e}`),t(e)}),(()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.engine.emitEvent("bufferStalled"),this.errsBufStalled++}increMediaRequests(){this.mediaRequests++,this.engine.emit(e.MEDIA_REBUFFER,this.errsBufStalled>=2)}reportFlow(e){const t=Math.round(e/1024);this.engine.emitEvent("httpDownloaded",t),this[tt]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const s=Math.round(e/1024);this[st]+=s,this.totalP2PDownloaded+=s,this.health.recordP2p(s),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",s,this.speed),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.engine.emitEvent("p2pUploaded",t),this.totalP2PUploaded+=t,this.health.recordShare(t),this[it]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){const{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:s}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:s,p2pDownloadSpeed:this.speed});const{getStats:i}=this.config;P(i)&&i(t,s,e,this.speed)}_makeStatsBody(){let e={totalConns:this.engine.tracker.totalConns+1,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,http:Math.round(this[tt])||0,p2p:Math.round(this[st])||0,share:Math.round(this[it])||0},t={};this.engine.getExtraForStats&&(t=this.engine.getExtraForStats()),e=Object.assign({},e,t),this.lastStats=JSON.parse(JSON.stringify(e)),Object.keys(e).forEach((t=>{0===e[t]&&delete e[t]}));const{logger:s}=this.engine;return s.isDebugLevel&&s.info(`report ${JSON.stringify(e)}`),this[st]>1e6&&(this.bigValueReported=!0),e}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":lt(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const nt=rt;function at(e,t){const s=ot();return(at=function(e,t){return s[e-=0]})(e,t)}function ot(){const e=["CsLPpZ8932212".split("").reverse().join(""),"htgnel".split("").reverse().join(""),"UZpUzY5895021".split("").reverse().join(""),"yJZuxA9452121".split("").reverse().join(""),"tAedoCrahc".split("").reverse().join(""),"btoa","q#<K@C".split("").reverse().join(""),"1164HyWkyu","4154136SJSwNe","IITNvu6344771".split("").reverse().join(""),"edoCrahCmorf".split("").reverse().join(""),"554Biqadw","oShtCc7412072".split("").reverse().join("")];return(ot=function(){return e})()}function lt(e){if(!e)return;const t=at(-822- -830,-826);let s="".split("").reverse().join("");const i=t.length;for(let r=0;r<e.length;r++){const n=e.charCodeAt(r)^t.charCodeAt(r%i);s+=String.fromCharCode(n)}return self.btoa(s)}function ht(e,t,s,i,r,n,a,o){let l;t={...t},s&&(l=dt(s,i)),fetch(e,{method:"POST",headers:t,body:l}).then((e=>{e.ok?(r&&r(!0),e.arrayBuffer().then((e=>{let t;try{t=new $e(e).readFields(Ke,{ret:0},s);const i=t[t.data];delete t[t.data],t.data=i}catch(s){try{const s=new TextDecoder("utf-8").decode(e);t=JSON.parse(s)}catch(e){t=null}}var s;n&&n(t)}))):r&&r(!1,e.status)})).catch((e=>{a&&a(e)})).finally((()=>{o&&o()}))}function dt(e,t){const s=new $e;t(e,s);return s.finish()}!function(e,t){const s=e();function i(e,t,s,i,r){return at(e-92,r)}function r(e,t,s,i,r){return at(r-930,s)}for(;;)try{if(377468===parseInt(r(0,0,944,0,939))/1*(parseInt(r(0,0,936,0,930))/2)+parseInt(r(0,0,929,0,935))/3+parseInt(r(0,0,939,0,941))/4+-parseInt((n=-995,a=-995,at(n- -999,a)))/5+parseInt(i(94,0,0,0,91))/6+-parseInt(i(93,0,0,0,92))/7+-parseInt(i(102,0,0,0,107))/8)break;s.push(s.shift())}catch(e){s.push(s.shift())}var n,a}(ot);class ct extends(n()){constructor(e,t){super(),this.logger=e,t.startsWith("wss")?this.addr=t.replace("wss","https"):t.startsWith("ws")&&(this.addr=t.replace("ws","http")),this.connected=!1,this.retryCount=0,this.closed=!1,this.msgQueue=[],this.posting=!1,this.pollingTs=0}start(){this.closed=!1,this._hello((()=>{this._longPolling()}))}_hello(e){fetch(this.addr+"&hello",{method:"POST"}).then((e=>{if(!e.ok)throw new Error("hello response was not ok");return e.json()})).then((t=>{this.connected=!0,e(),this.onopen&&this.onopen(t.ver)})).catch((e=>{this.closed=!0,this.onerror&&this.onerror(e)}))}send(e){this.msgQueue.push(e),this.posting||this._realSend([...this.msgQueue])}_realSend(e){0!==e.length&&(this.posting=!0,this.msgQueue=[],fetch(this.addr,{method:"POST",body:JSON.stringify(e)}).then((()=>{this.posting=!1,this.msgQueue.length>0&&this._realSend([...this.msgQueue])})).catch((e=>{this.logger.error(e),this.posting=!1})))}close(){this.connected&&(this.closed=!0,this.connected=!1,this.abortController&&(this.abortController.abort(),this.abortController=null),this.onclose&&this.onclose())}destroy(){this.close(),this.removeAllListeners()}_longPolling(){if(this.closed)return;this.pollingTs=p(),this.abortController=new AbortController;const e=this.abortController.signal;fetch(this.addr,{signal:e}).then((e=>{if(!e.ok)throw new Error("polling response was not ok");return e.text()})).then((async e=>{e&&this.onmessage&&this.onmessage(JSON.parse(e)),this.retryCount=0;const t=p()-this.pollingTs;JSON.stringify(e)===JSON.stringify(this.lastData)&&t<10&&(this.logger.warn(`wait ${10-t}s for next polling`),await v(1e3*(10-t))),this.lastData=e,this._longPolling()})).catch((e=>{this.connected&&(this.retryCount<=3?(this.retryCount++,this._longPolling()):(this.connected=!1,this.onerror&&this.onerror(e)))}))}}const ut=class{constructor(e,t,s,i="main"){this.logger=e,this.config=t,this.wsAddr=s,this.serverVersion=0,this.pingInterval=95e3,this.name=i,this.normalClosed=!1,this.connecting=!0,this.lastSendTs=performance.now(),this.pollingClient=new ct(e,s);try{this._ws=this._init()}catch(t){e.error(t),this._startPolling()}}get batchSupported(){return this.serverVersion>=50}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:m(15e3,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20,connectionTimeout:7e3};let t=new B(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.normalClosed=!1,this.connecting=!1,this.pollingClient.connected?this.pollingClient.close():this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{this.lastSendTs=performance.now();let s=JSON.stringify(e);t.push(s)},t.addEventListener("message",(e=>{let t=e.data;const s=JSON.parse(t),i=s.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${s.reason}`),void this.close()):void("signals"!==i?this.onmessage&&this.onmessage(s,this.name):this._onSignalBatch(s.data));this.serverVersion=s.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{const{code:t,reason:s}=e;this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${t} ${s}`),t>=5e3||t<4e3?(this.onclose&&this.onclose(),this._stopPing()):this.close(),this.connecting=!1})),t.addEventListener("error",(e=>{this._stopPing(),this.onerror&&this.onerror(e),this._startPolling()})),t}_startPolling(){this.normalClosed||this.pollingClient.connected||(this.logger.info(`${this.name} start polling`),this.pollingClient.start(),this._setupPolling(this.pollingClient))}sendDebug(e,t,s){this._send({action:"debug",details:t,ping:s||void 0,to:e})}sendSignal(e,t){const s={action:"signal",to:e,data:t};this._send(s)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let s of t)this.sendSignal(e,s)}sendReject(e,t,s){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const i={action:"reject",to:e,reason:t,fatal:s};this._send(i)}_send(e){this.pollingClient.connected?this.pollingClient.send(e):this._ws&&this._ws.send(e)}_startPing(e){this.connected&&(this.pingTimer=setTimeout((()=>{const e=95e3-(performance.now()-this.lastSendTs);if(e>=0)return this._startPing(e);const t={action:"ping"};this._ws&&this._ws.push(JSON.stringify(t)),this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3),this._startPing(this.pingInterval)}),e))}_stopPing(){clearTimeout(this.pingTimer),clearTimeout(this.pongTimer)}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3)})(),this.pollingClient.close(),this.normalClosed=!0}reconnect(){return!(!this._ws||this.connecting)&&(this.connecting=!0,this.normalClosed=!1,this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect(),!0)}destroy(){this.close(),this._ws=null,this.pollingClient.destroy()}get connected(){return!!this.pollingClient.connected||this._connected}get _connected(){return!!this._ws&&this._ws.readyState===B.OPEN}_setupPolling(e){e.onopen=e=>{e&&(this.serverVersion=e),this.logger.info(`${this.name} polling opened`),this.connecting=!1,this.onopen&&this.onopen()},e.onerror=e=>{this._connected||this.onerror&&this.onerror(e)},e.onclose=()=>{this._connected||this.onclose&&this.onclose()},e.onmessage=e=>{if(this.onmessage)for(let t of e)"signals"===t.action?this._onSignalBatch(t.data):this.onmessage(t,this.name)}}_onSignalBatch(e){if(this.onmessage)for(let t of e)t.action||(t.action="signal"),this.onmessage(t,this.name)}},ft=class{constructor(e,t,s,i){this.logger=e,this.config=t,this.mainAddr=s,this.backupAddr=i,this.mainWS=this._init(s),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(i,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let s=new ut(this.logger,this.config,e,t);return s.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},s.onmessage=e=>{this.onmessage&&this.onmessage(e,s.name)},s.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},s.onerror=e=>{this.onerror&&this.onerror(e)},s}sendSignalBatch(e,t,s){if(s){const i=this._getWSByName(s);i&&i.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,s){this.sendSignalBatch(e,[t],s)}sendReject(e,t,s,i){if(i){const r=this._getWSByName(i);if(r)return void r.sendReject(e,t,s)}this.mainConnected?this.mainWS.sendReject(e,t,s):this.backupConnected?this.backupWS.sendReject(e,t,s):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,s){this.mainConnected&&this.mainWS.sendDebug(e,t,s)}close(){this.mainWS&&this.mainWS.close(),this.backupWS?this.backupWS.close():this.backupTimer&&clearTimeout(this.backupTimer),this.normalClosed=!0}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(e){let t=!1;return this.mainWS&&"backup"!==e&&this.mainWS.reconnect()&&(t=!0),this.backupWS&&"main"!==e&&this.backupWS.reconnect()&&(t=!0),t}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}get connecting(){let e=!1;return this.mainWS&&this.mainWS.connecting&&(e=!0),this.backupWS&&this.backupWS.connecting&&(e=!0),e}};const gt=function(e,t,s=40){var i=null,r=!1,n=s;return function(s=!1){if(s)return clearTimeout(i),void(r=!1);r||(r=!0,i=setTimeout((function(){e.call(t,n),r=!1,i=null}),1e3*n),n*=1.1)}};class pt{constructor(e,t,s=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=s,this.pool=[],t.ICEPreflight&&this.reset(),this.trickle=!1}reset(){this.destroy();for(let e=0;e<this.poolSize;e++)this.pool.push(this._createPeer())}_createPeer(){return new ee(this.engine,void 0,void 0,!0,this.config,{trickle:this.trickle})}get available(){return 0!==this.pool.length&&this.pool[0].signalMsgs.length>0}getPeer(){if(0===this.pool.length)return this._createPeer();const e=this.pool.shift();return this.pool.length<5&&this.pool.push(this._createPeer()),e}destroy(){for(let e of this.pool)e.destroy(!0);this.pool=[]}}const mt=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,s=0,i="";for(const r of e){if("="===r)break;const e=this.CHARSET.indexOf(r);for(t=t<<this.BITS_PER_BASE64_CHAR|e,s+=this.BITS_PER_BASE64_CHAR;s>=this.BITS_PER_BYTE;){s-=this.BITS_PER_BYTE;i+=(t>>s&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let r="";for(let e=0;e<i.length;e++)r+=i[e],e%2==1&&e!==i.length-1&&(r+=":");return r}},vt="typ host",yt="generation 0",Et="network-cost",St="rport",Tt="0.0.0.0",_t={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},Lt={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},bt={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},Rt={P:`${vt} ${yt} ${Et} 999`,W:`${St} 0 ${yt} ${Et} 999`,H:vt,S:"typ srflx",R:St,A:"raddr",V:Tt,F:"ufrag",G:`${St} 0 ${yt}`,N:Et,E:"network-id",C:"tcptype active",Q:`${yt}`,U:"udp",T:"tcp"},At={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Pt={4:"IP4",6:"IP6"},wt={0:Tt},It=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in Rt&&(e=Rt[e]),e))).join(" "));function Dt(e,t){let s=e.split("~"),i=[];s=s.map((e=>{let t=e.slice(0,1),s=e.slice(1);if(t in _t&&(t=_t[t]),"a="===t){let e=s.slice(0,1);const t=s.slice(1);e in Lt&&(e=Lt[e],s=e+t)}return t+s})),i.push("v=0"),i.push("s=-"),i.push("t=0 0"),i.push("a=msid-semantic: WMS");let r=0;s.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),s=[];s.push("-");const r=t.shift();if(r&&s.push(r),0===t.length)s.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&s.push(e),0===t.length)s.push("IN IP4 127.0.0.1");else{s.push("IN");const e=t.shift();e&&s.push(e);const i=t.shift();i&&s.push(i)}}i.splice(1,0,`o=${s.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(Ct,(e=>At[e]))}(e),i.push(e),i.push("a=setup:"+(t?"actpass":"active")),i.push(`a=mid:${r}`),void r++;if(e.startsWith("a=candidate:"))return e=It(e),void i.push(e);if(e.startsWith("a=fingerprint:")){let[t,s]=e.slice(14).split(" ");return t in bt&&(t=bt[t]),s=mt.decode(s),void i.push(`a=fingerprint:${t} ${s}`)}if(e.startsWith("c=")){let[t,s]=e.slice(2).split(" ");return t in Pt&&(t=Pt[t]),s in wt&&(s=wt[s]),void i.push(`c=IN ${t} ${s}`)}"I"!==e?"Z"!==e?"B"!==e?i.push(e):i.push("a=sendrecv"):i.push("a=ice-options:ice2,trickle"):i.push("a=ice-options:trickle")}}));const n=i.length-1;return i.splice(n,0,`a=group:BUNDLE ${Array.from(Array(r).keys()).join(" ")}`),i.join("\r\n")}const Ct=new RegExp(Object.keys(At).join("|"),"g");class kt extends(n()){constructor(e,t,s,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=s,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set,this.isMobile=e.isMobileNet,this.peerPool=new pt(e,i,10),this.signalerWs=null,this.fetcher=t,this.peers=[],this.minConns=8,this.stuns=[],this.requestMorePeers=gt(this._requestMorePeers,this,m(35,45)),this.maxConns=this.isMobile?15:20,this.maxConnsActive=this.isMobile?12:13,this.fuseRate=-1,this.overloaded=!1,this.signalRejectCache="",this.maxPeersBySignalServer=12,this._startCheckConnsTimer()}get totalConns(){return this.scheduler.peersNum}get isReachActiveLimit(){return this.DCMap.size>=this.maxConnsActive}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:s,fetcher:i}=this,{wsSignalerAddr:r,wifiOnly:n}=s;i.btAnnounce().then((e=>{const{scheduler:s}=this;if(!s)return;t.peerId=this.peerId=e.id,e.min_conns&&(this.minConns=e.min_conns);const i=e.peers||[];s.notifyPeersLoaded(i.length),(e.wifi_only||n)&&this.isMobile&&(s.downloadOnly=!0,this.logger.info("downloadOnly mode"));const a=r.main;let o=r.backup;e.signal&&!e.signal2&&(o=void 0),this.signalerWs=this._initSignalerWs(e.signal||a,e.signal2||o,e.token,e.token2),0===i.length?this.requestMorePeers():this.peers=i,t.emitEvent("peerId",this.peerId),e.stun&&e.stun.length>0&&(this.stuns=e.stun),e.debug&&(this.logger.enableDebug(),e.log_url&&(this.logUploader=new G(e.log_url,this.fetcher.key||location.hostname,this.peerId,"2.17.10"),this.logger.setUploader(this.logUploader))),t.onTrackerResume&&t.onTrackerResume(e),e.fuse_rate&&(this.maxConnsActive=this.fuseRate=e.fuse_rate,this.maxConns=this.maxConnsActive+(this.isMobile?3:7),this.maxPeersBySignalServer=7),e.overload&&(this.overloaded=!0,this.maxPeersBySignalServer=3,this.logger.warn("server overloaded, degrade signaling")),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`)})).catch((s=>{if(this.scheduler&&("TRACKER_EXPT"===s.code&&t.emitEvent(e.EXCEPTION,s),this.scheduler.notifyPeersLoaded(0),s.retry)){const e=m(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){clearInterval(this.checkConnsTimer),this.fetcher.postStatsWithBeacon(),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.peerPool.destroy(),this.peerPool=null,this.failedDCMap.clear(),this.notFoundDCSet.clear(),this.logUploader&&(this.logUploader.destroy(),this.logUploader=null),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")}isPeerConnectedOrFailed(e){return!e||(this.DCMap.has(e)||this.failedDCMap.has(e)||e===this.peerId)}_filterPeers(e){return e.filter((e=>!this.isPeerConnectedOrFailed(e.id)))}_tryConnectToAllPeers(){const{logger:e}=this,t=this.totalConns;if(!(t>=this.maxConnsActive))if(0!==this.peers.length){for(this._checkDCMap(),e.info(`try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${t}`),this.peersTemp=[];this.peers.length>0&&!this.isReachActiveLimit;){let t=this.peers.shift();const s=t.intermediator;if(!this.isPeerConnectedOrFailed(t.id)){if(!s||!this.DCMap.has(s)){let s=!1;if(this.signalerWs.connected||(s=!0,e.info(`skip peer ${t.id} without intermediator`)),[...this.DCMap.values()].filter((e=>!e.byPeerSignal&&!e.connected)).length>=this.maxPeersBySignalServer&&(s=!0,e.warn(`skip peer ${t.id} by signal server`)),s){this.peersTemp.push(t);continue}}e.debug(`create DataChannel ${t.id} intermediator ${s}`),this._createDatachannel(t.id,!0,s)}}this.peers.push(...this.peersTemp)}else e.info("no peers after filter")}_handleSendSignal(e,t){const s=e.remotePeerId;if(e.intermediator){const i=this.DCMap.get(e.intermediator);if(i){let r=!0;for(let e of t)i.sendMsgSignal(s,this.peerId,e)||(r=!1);if(r)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(s,t,e.signalName)}_setupDC(t){t.on(e.DC_SIGNAL,(e=>{this._handleSendSignal(t,[e])})).on(e.DC_SIGNAL_BATCH,(e=>{this._handleSendSignal(t,e)})).on(e.DC_PEER_SIGNAL,(e=>{const s=e.to_peer_id||e.to,i=e.from_peer_id||e.from,r=e.action;if(s&&i&&r)if(s!==this.peerId){this.logger.info(`relay signal for ${i}`);const n=this.DCMap.get(s);if(n){if("signal"!==r)return void n.sendMsgSignalReject(s,i,e.reason,e.fatal);if(n.sendMsgSignal(s,i,e.data))return}t.sendMsgSignal(i,s)}else"signal"===r?this._handleSignalMsg(i,e,t.remotePeerId):this._handSignalRejected(i,e)})).on(e.DC_GET_PEERS,(()=>{const e=this._gatherPeersToSent(t);this.logger.info(`send ${e.length} peers to ${t.remotePeerId}`),t.sendPeers(e)})).once(e.DC_ERROR,((e,s)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${s}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCMap.set(t.remotePeerId,`DC_FAILED ${s}`),this._doSignalFusing(this.totalConns),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:s,data:i})=>{const{logger:r}=this,{remotePeerId:n,useBackupSignal:a,isInitiator:o}=t;if(s&&e&&o&&(this.failedDCMap.set(n,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!this.isReachActiveLimit&&!e&&o&&!a&&this._tryBackupSignal(t,n,i,t.signalName))return t._startTimer(),void r.warn(`${n} conn timeout, try backup signal`);this._destroyAndDeletePeer(n,!1),o&&this._doPeersRequest()})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.totalConns)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCMap.set(t.remotePeerId,"DC_CLOSE"),this._doPeersRequest()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler&&this.scheduler.handshakePeer(t,this._gatherPeersToSent(t))})).once(e.DC_METADATA,(e=>{const{scheduler:s}=this;if(!s)return;t.isInitiator||s.handshakePeer(t,this._gatherPeersToSent(t)),s.handleMetaData(t,e);const i=this.isReachActiveLimit;i||this._handleRequestedPeers(this._handleSharedPeers(t,e.shared_peers))>0&&this._tryConnectToAllPeers(),this.requestMorePeers(i);const r=this.totalConns;this._doSignalFusing(r),r>=this.maxConns&&this.fuseRate<0&&this.fetcher.postStats(!0)&&this.logger.warn(`peers reach ${r}, report`)}))}_doPeersRequest(){this.peers.length<this.maxConnsActive-this.DCMap.size&&this._gatherSharedPeersFromPeers(),(0===this.peers.length||this.totalConns<this.minConns)&&this.requestMorePeers(),this._tryConnectToAllPeers()}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate?(this.logger.warn("reach fuseRate, close signaler"),this.totalConns>0&&this.fetcher.postStats(!0),this.signalerWs.close()):!t&&e<=this.minConns&&!this.signalerWs.connecting&&this.signalerWs.reconnect()&&(this.logger.warn(`low conns ${e}, reconnect signaler`),this.fetcher.postStats(!0))}_initSignalerWs(t,s,i,r){const n=(e,t)=>{let s=`${e}?id=${this.peerId}&p=web&v=2.17.10&b=1`;return this.config.signalCompact&&(s=`${s}&c=1`),t&&(s=`${s}&token=${t}`),s};let a,o=n(t,i);if(s&&s!==t){let e=n(s,r);a=new ft(this.logger,this.config,o,e)}else a=new ut(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let s=e.action;const i=e.from_peer_id||e.from;if(i)switch(s){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`Signal websocket unknown action ${s}`)}else this.logger.warn("fromPeerId is missed")},a.onclose=()=>{this.connected=!1},a.onerror=t=>{t.message&&this.logger.warn(`signal err: ${t.message}`),t.message&&this.engine.emitEvent(e.EXCEPTION,Oe(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const s=`signaling ${e} rejected`;this.logger.warn(`${s}, reason ${t.reason}`);const i=this.DCMap.get(e);i&&!i.connected&&(i.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,s),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,s,i){return!(!(this.signalerWs.backupConnected&&e&&s.length>0&&"main"===i)||e.useBackupSignal)&&(e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,s,"backup"),!0)}_handleSignalMsg(e,t,s,i){if(!this.scheduler)return;const{logger:r}=this;if(t.data){if(this.failedDCMap.has(e))return void this._sendSignalReject(e,`${e} ${this.failedDCMap.get(e)||"unknown"}`,s,i,!0);this._handleSignal(e,t.data,s,i)}else{const t=this.DCMap.get(e);if(!t)return;if(!this.isReachActiveLimit&&this._tryBackupSignal(t,e,t.signalMsgs,i))return void this.logger.warn(`${e} not found from ${i}, try backup signal`);if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),r.info(`signaling ${e} not found`);const{scheduler:n}=this;if(n.waitForPeer&&(n.waitingPeers--,0===n.waitingPeers&&n.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),s){const t=this.DCMap.get(s);t&&t.notFoundPeers.add(e)}else this.notFoundDCSet.add(e)}}_handleSignal(e,t,s,i){let r=t;"string"==typeof r?r=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:It(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),s="O"===e[0];return{type:s?"offer":"answer",sdp:Dt(t,s)}})(r):t=void 0;const n=r.type,{logger:a}=this;let o=this.DCMap.get(e);if(o){if(o.connected)return void a.info("datachannel had connected, signal ignored");if("offer"===n&&o.isInitiator){if(!(this.peerId>e))return void a.warn(`${e} signal type wrong ${n}, ignored`);a.warn(`${e} signal type wrong ${n}, convert to non initiator`),this._destroyAndDeletePeer(e,!1),o=this._createDatachannel(e,!1,s)}}else{if("answer"===n){const t=`${e} type wrong ${n}`;return a.warn(t),this._sendSignalReject(e,t,s,i),void this._destroyAndDeletePeer(e,!1)}if(a.debug(`receive node ${e} connection request`),this.DCMap.size>=this.maxConns){const t=`reach limit ${this.maxConns}`;return a.warn(t),void this._sendSignalReject(e,t,s,i,!0)}o=this._createDatachannel(e,!1,s)}o&&(i&&(o.signalName=i),o.receiveSignal(r,t))}_createDatachannel(e,t,s){if(!this.fetcher)return;let i;if(t&&this.peerPool.available)i=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${i.signalMsgs.length}`),i.intermediator=s,i.assignPeerId(this.peerId,e);else{let r=this.config.trickleICE;this.overloaded&&(r=!1),i=new ee(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:s,trickle:!s&&r})}return this.DCMap.set(e,i),this._setupDC(i),i}_sendSignalReject(e,t,s,i,r){if(this.signalRejectCache!==e){if(s){const i=this.DCMap.get(s);if(i&&i.sendMsgSignalReject(e,this.peerId,t,r))return}this.signalerWs.sendReject(e,t,r,i),this.signalRejectCache=e}}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this;if(this._checkDCMap(),this.isReachActiveLimit)return;this._gatherSharedPeersFromPeers();const s=this.peers.length,i=this.totalConns;i<this.minConns&&(0===s||i+s<=this.maxConnsActive)&&this.signalerWs.connected?(t.info(`requestMorePeers after delay ${e} peersNum ${i}`),this._requestPeersFromServer(i)):t.info(`skip requestMorePeers peersNum ${i} try peers ${s}`),this._tryConnectToAllPeers()}_requestPeersFromServer(e){const{logger:t}=this;this.failedDCMap.size>50&&(this.failedDCMap=new Map([...this.failedDCMap].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCMap.keys(),...this.notFoundDCSet.keys()],0===e).then((e=>{e&&e.peers&&(t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers())})).catch((e=>{t.error(`requestMorePeers error ${e}`)}))}_handleRequestedPeers(e=[],t=!1){if(this.fetcher){if(e.length>0){const s=function(e,t){const s=[],i=new Set;for(let t of e)i.has(t.id)||(i.add(t.id),s.push(t));const{asn:r,country:n}=t;if(!r||!n||s.length<2)return s;const a=s.filter((e=>!e.asn&&!e.country)),o=s.filter((e=>e.country===n&&e.asn!==r)),l=s.filter((e=>e.asn===r&&e.country===n)),h=s.filter((e=>!a.includes(e)&&!l.includes(e)&&!o.includes(e)));return l.concat(o).concat(a).concat(h)}(e,this.fetcher.announceInfo);return t?this.peers=s:this.fuseRate>0?this.peers=[...s,...this.peers]:this.peers=[...this.peers,...s],this.logger.info(`after filtered total ${s.length}`),s.length}return 0}}_destroyAndDeletePeer(e,t=!0){const s=this.DCMap.get(e);return!!s&&(s.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=p();for(let t of this.DCMap.values()){const s=e-t.timeJoin;e-t.timeJoin>20&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${s} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}_filterFullPeers(){return this.scheduler.getPeers().filter((e=>e.peersConnected<(this.fuseRate<0?e.mobileWeb?14:19:this.maxConns)&&!e.super))}_filterImmaturePeers(e,t,s){const i=[];return e.forEach((e=>{if(e.remotePeerId===t.remotePeerId||e.remotePeerId===this.peerId)return;if(!this.config.live&&(e.currentPos-t.currentPos>600||e.currentPos<t.currentPos))return;s-e.timeJoin>40&&i.push({id:e.remotePeerId,...e.region})})),i}_gatherPeersToSent(e){const t=this._filterFullPeers();return this._filterImmaturePeers(t,e,p())}_handleSharedPeers(e,t){const s=[];return t&&t.length>0&&(this.logger.info(`receive ${t.length} peers from ${e.remotePeerId}`),t.forEach((t=>{t.intermediator=e.remotePeerId})),s.push(...this._filterPeers(t))),s}_startCheckConnsTimer(){const{scheduler:e}=this;this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const t=this.scheduler.getStatsForPeer();let s=this.totalConns;const i=p(),r=this._filterFullPeers();e.getPeers().forEach((e=>{s>this.minConns+1&&(i-e.dataExchangeTs>120||i-e.gotStatsTs>=103)?(this.logger.warn(`close dead peer ${e.remotePeerId} level ${e.currentLevel}`),e.close(!1),s--):e.connected&&e.sendMsgStats(s,this._filterImmaturePeers(r,e,i),t)}))}),5e4)}_gatherSharedPeersFromPeers(){const e=[],t=new Set,s=this.scheduler.getPeers();s.sort((()=>Math.random()-.5)).forEach((s=>{const i=this._handleSharedPeers(s,s.currentSharedPeers).filter((e=>!t.has(e.id)&&(t.add(e.id),!0)));e.push(...i)})),e.length>0&&(this.logger.info(`gather shared peers total ${e.length}`),0===this._handleRequestedPeers(e,!0)&&s.forEach((e=>{e.clearCurrentSharedPeers()})))}}const Mt=kt;class xt extends re{constructor(e={},t=null){if(super(e),e.validateSegment||(e.validateSegment=function(e,t){return!0}),this.hlsjs=t,this.config=Object.assign({useDiskCache:!e.live},fe,e),t){this.HLSEvents=t.constructor.Events;const e=t.constructor.version;this.hlsjsVersion=e,this.config.isHlsV0=e&&"0"===e.split(".")[0]}this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t}=this.config,s=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(s=this.makeChannelId(e,t));return{channelIdMaker:s,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo}}}setupElectron(){this.browserInfo.device===Q.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();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=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(e){const{logger:s,config:i}=this;if(self.indexedDB&&i.useDiskCache&&!i.live){const e=new De(this,i);try{await e.setupStore(),this.bufMgr=e}catch(e){s.warn(e),this.bufMgr=new Me(this,i)}}else this.bufMgr=new Me(this,i);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid");"SegmentStore"===this.bufMgr.name&&(this.removeAllListeners(t.BM_FATAL_ERROR),this.once(t.BM_FATAL_ERROR,(()=>{s.warn("SegmentStoreFatalError, switch to SegmentCache"),this.bufMgr.destroy(),this.bufMgr=new Me(this,i),e&&e(this.bufMgr)})))}generateTag(){let e=(0,Q.getBrowser)();return e.includes("iPhone")&&"HlsSwP2pEngine"===this.engineName&&(e=`${e}_p`),this.playerName&&(e=`${e}_${this.playerName}`),e}async _init(e,t,s){const{logger:i,config:r}=this;if(!re.isSupported())throw new Error("webrtc is not supported");await this.initSegmentManager((e=>{if(this.tracker){const{scheduler:t}=this.tracker;t.bufferManager=e,t.bitset.clear()}})),s.live||this.media&&(s.pos=Math.round(this.media.currentTime)),s.tag=void 0===r.tag?this.generateTag():r.tag;let n=new nt(this,r.token,encodeURIComponent(e),r.announce||"",s);this.fetcher=n,this.tracker=new Mt(this,n,t,r),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?de:he)}_onHlsError(e,s){if(!s||!this.hlsjs)return;const{logger:i,tracker:r,config:n}=this;if(!i)return;const a=`${s.type} fatal ${s.fatal} details ${s.details} reason ${s.reason}`;if(s.fatal?i.error(a):i.warn(a),"networkError"===s.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:o}=this.browserInfo,l=`${o||""} hlsjs ${this.hlsjsVersion} ${location.href}`,h=this.hlsjs.constructor.ErrorDetails;switch(s.details){case h.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),r&&r.scheduler){const e=r.scheduler;i.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case h.INTERNAL_EXCEPTION:if(s.event&&"demuxerWorker"!==s.event){s.error||(s.error={});const e=`${s.error.message} event ${s.event} ${l}`;i.error(`INTERNAL_EXCEPTION event ${s.event} err ${s.error.message}`),this.emitEvent(t.EXCEPTION,Oe(s.error,"HLSJS_EXPT")),i.report(e,s.event,this.peerId,"2.17.10")}break;default:const e=s.details===h.FRAG_PARSING_ERROR;if(s.fatal||e){"mediaError"===s.type&&r&&r.scheduler&&r.scheduler.disconnectLoadingPeer(void 0,this.peerId).then((e=>{e&&r.scheduler.clearCache()}));const e=`${s.type} ${s.details} ${s.err||""} ${l}`;i.report(e,s.details,this.peerId,"2.17.10")}}}}class Ot{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=o.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class Ft{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[Ft.ElementaryStreamTypes.AUDIO]:!1,[Ft.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=o.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 s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let s=e;return e&&e.method&&e.uri&&!e.iv&&(s=new Ot,s.method=e.method,s.baseuri=e.baseuri,s.reluri=e.reluri,s.iv=this.createInitializationVector(t)),s}}class Nt{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 $t=/^(\d+)x(\d+)$/,Bt=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class Ut{constructor(e){"string"==typeof e&&(e=Ut.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 s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}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=$t.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,s={};for(Bt.lastIndex=0;null!==(t=Bt.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),s[t[1]]=e}return s}}const Gt=Ut,Ht={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};const Vt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Wt=/#EXT-X-MEDIA:(.*)/g,qt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),jt=/(?:(?:#(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?/,zt=/\.(mp4|m4s|m4v|m4a)$/i;class Kt{static findGroup(e,t){if(!e)return null;let s=null;for(let i=0;i<e.length;i++){const r=e[i];r.id===t&&(s=r)}return s}static convertAVC1ToAVCOTI(e){let t,s=e.split(".");return s.length>2?(t=s.shift()+".",t+=parseInt(s.shift()).toString(16),t+=("000"+parseInt(s.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let s,i=[];function r(e,t){["video","audio"].forEach((s=>{const i=e.filter((e=>function(e,t){const s=Ht[t];return!!s&&!0===s[e.slice(0,4)]}(e,s)));if(i.length){const r=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${s}Codec`]=r.length>0?r[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(Vt.lastIndex=0;null!=(s=Vt.exec(e));){const e={},n=e.attrs=new Gt(s[1]);e.url=Kt.resolve(s[2],t);const a=n.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=n.decimalInteger("AVERAGE-BANDWIDTH")||n.decimalInteger("BANDWIDTH"),e.name=n.NAME,r([].concat((n.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=Kt.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,s,i=[]){let r,n=[],a=0;for(Wt.lastIndex=0;null!==(r=Wt.exec(e));){const e={},o=new Gt(r[1]);if(o.TYPE===s){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=s,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Kt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=Kt.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,n.push(e)}}return n}static parseLevelPlaylist(e,t){let s,i,r=0,n=0,a=new Nt(t),o=new Ot,l=0,h=null,d=new Ft,c=null;for(qt.lastIndex=0;null!==(s=qt.exec(e));){const e=s[1];if(e){d.duration=parseFloat(e);const t=(" "+s[2]).slice(1);d.title=t||null,d.tagList.push(t?["INF",e,t]:["INF",e])}else if(s[3]){if(Number.isFinite(d.duration)){const e=r++;d.start=n,d.levelkey=o,d.sn=e,d.cc=l,d.baseurl=t,d.relurl=(" "+s[3]).slice(1),Yt(d,h),a.fragments.push(d),h=d,n+=d.duration,d=new Ft}}else if(s[4]){if(d.rawByteRange=(" "+s[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(d.lastByteRangeEndOffset=e)}}else if(s[5])d.rawProgramDateTime=(" "+s[5]).slice(1),d.tagList.push(["PROGRAM-DATE-TIME",d.rawProgramDateTime]),null===c&&(c=a.fragments.length);else{for(s=s[0].match(jt),i=1;i<s.length&&void 0===s[i];i++);const e=(" "+s[i+1]).slice(1),n=(" "+s[i+2]).slice(1);switch(s[i]){case"#":d.tagList.push(n?[e,n]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":r=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 u=new Gt(e),f=u.enumeratedString("METHOD"),g=u.URI,p=u.hexadecimalInteger("IV");f&&(o=new Ot,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 Gt(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let h=new Gt(e);d.relurl=h.URI,d.rawByteRange=h.BYTERANGE,d.baseurl=t,d.sn="initSegment",a.initSegment=d,d=new Ft,d.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${s}`)}}}return d=h,d&&!d.relurl&&(a.fragments.pop(),n-=d.duration),a.totalduration=n,a.averagetargetduration=n/a.fragments.length,a.endSN=r-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>zt.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),d=new Ft,d.relurl=a.fragments[0].relurl,d.baseurl=t,d.level=id,d.sn="initSegment",a.initSegment=d,a.needSidxRanges=!0),c&&function(e,t){let s=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(a.fragments,c),a}}function Yt(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)}class Xt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const s=Number(e);if(s<0)continue;const i=new Map;if(t[e])for(let s of t[e])i.set(s,{state:d.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(s,i)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,s,i=d.ANY){if(t<0)return!1;const r=this._createOrGetSet(t).get(e);return!!r&&((!s||!r.segId||r.segId===s)&&(i===d.ANY||r.state===i))}has(e,t,s=d.ANY){return this.hasWithId(e,t,void 0,s)}hasCompleteOr(e,t,s=d.COMPLETE){const i=this._createOrGetSet(t).get(e);return!!i&&(i.state===d.COMPLETE||i.state===s)}getObj(e,t){let s=this._createOrGetSet(t).get(e);return s||(s={}),s}getSegId(e,t){return this.getObj(e,t).segId}getSize(e,t){return this.getObj(e,t).size}getState(e,t){return this.getObj(e,t).state}delete(e,t){return this._createOrGetSet(t).delete(e)}deleteOlderThan(e,t){const s=this._createOrGetSet(t);s.forEach(((t,i)=>{i<=e&&s.delete(i)}))}add(e,t,s,i,r){if("number"!=typeof(n=e)||n%1!=0)return;var n;this._createOrGetSet(t).set(e,{state:i,segId:s,size: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,s)=>{e[s]=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-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[s,i]of e)i.state===d.COMPLETE&&t.push(s);return t}}class Qt{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 s=this._createOrGetMap(t);if(s.has(e)){let t=s.get(e);1===t?s.delete(e):s.set(e,t-1)}}incre(e,t){const s=this._createOrGetMap(t);if(s.has(e)){let t=s.get(e);s.set(e,t+1)}else s.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}}const Jt=class{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))}},Zt=Symbol("shareOnly");class es extends(n()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Jt,this.fragLoading=!1,this._setupEngine&&this._setupEngine(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[Zt]=!1,this.downloadOnly=!1,this.loadedPeerNum=0}get isMobileNet(){return this.engine.isMobileNet}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}chokePeerRequest(t){const s={event:e.DC_CHOKE};t?t.sendJson(s):this._broadcastToPeers(s)}unchokePeerRequest(t){const s={event:e.DC_UNCHOKE};t?t.sendJson(s):this._broadcastToPeers(s)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[Zt]=!0}deletePeer(e){e.downloading&&this._handlePieceAborted(e.remotePeerId),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[Zt]&&(e.choked=!0);const s=this.peerManager.getPeerIds();this._peersStats(s);const{asn:i,country:r}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${r||""} asn ${i||""}, now has ${s.length} peers`)}hasPeer(e){return this.peerManager.hasPeer(e)}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),t<this.peersNum){const t=this.peerManager.getPeers(),s=t.filter((e=>e.downloading));e.warn(`downloading: ${s.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of s)e.warn(`${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:e,segId:t,next:s,level:i})=>{this._broadcastLost(e,t,i),this.onBufferManagerLost(e,t,s,i)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,s,i,r){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:s||void 0,level:i},r)}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearTimeout(this.checkTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:s}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),s.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{s.warn(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),this._handlePieceAborted(t.remotePeerId),this.config.live&&this.checkPeers&&this.checkPeers()})).on(e.DC_DISCONNECT,(()=>{this.peersNum>=4&&(this.logger.warn(`close disconnected peer ${t.remotePeerId}`),t.close(!1))}))}_broadcastToPeers(e,t){for(let s of this.getPeers())t&&s===t||s.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;P(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(s=this.loadedPeerNum)?3:.5*s+1.67);var s;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const s=this.requestingMap.get(e);if(s)return void s.removeStreamListener(t);const i=this.segmentBuilderMap.get(e);i&&i.removeStreamListener(t)}setTargetPeersFromGroup(e,t,s,i){if(e.hasReversePeer){if((s=t.concat(s)).length>0)return this.targetPeers.forwardPeer=s[0],!0}else if(e.hasForwardPeer&&(i=t.concat(i)).length>0)return this.targetPeers.reversePeer=i[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=D(t,s,i),this.targetPeers.some((e=>!!e)))}}const ts=es;class ss extends(n()){constructor(){super(),this.internalMap=new Map}has(e){return this.internalMap.has(e)}set(e,t){this.internalMap.set(e,t),T(this.internalMap,13,(e=>{e&&e.destroy()}))}get(e){return this.internalMap.get(e)}delete(e){const t=this.internalMap.get(e);t&&(t.destroy(),this.internalMap.delete(e))}get size(){return this.internalMap.size}clear(){this.internalMap.clear(),this.removeAllListeners()}get activePeers(){let e=0;return[...this.internalMap.values()].forEach((t=>{t.hasForwardPeer&&!t.forwardCanceled&&(e+=1),t.hasReversePeer&&!t.reverseCanceled&&(e+=1)})),e}}const is=(e,t,s,i,r=!1)=>{const[n,a,o]=rs(e,t,s,i);return r&&n.length>=1?I(n[0]):n.length>=2?[n[0],n[1]]:D(n,a,o)},rs=(e,t,s,i)=>{const r=[],{COMPLETE:n,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=d;return[n,a,o].forEach((n=>{r.push(ns(e,n,t,s,i))})),r},ns=(e,t,s,i,r)=>e.filter((e=>e.bitset.hasWithId(s,i,r,t))),as=0,os=1,ls=2,hs=3;class ds extends(n()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,s)=>{e+=`${s}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0,this.emit("loadend")}send(){}_emitEvent(e){this.emit(e,{type:e,target:this})}}const cs=/(\d+)-(\d+)\/(\d+)/;function us(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class fs{constructor(e){this.fetchSetup=e.fetchSetup||gs,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=C(),this.packetSize=c,this.fakeXhr=new ds}destroy(){this.destroyed=!0,this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.xhrSetup=this.fakeXhr=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){if(this.destroyed)return;const i=this.stats;i.trequest=i.loading.start;let r=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return s}(e,(this.controller||{}).signal);const n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=s.onUpdate,d=s.onBodyStart;this.context=e,this.config=t,this.callbacks=s,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),r=function(e,t){e.withCredentials&&(t.credentials="include");for(let[s,i]of e.headers)t.headers.set(s,i);return t}(this.fakeXhr,r)),this.request=this.fetchSetup(e,r),clearTimeout(this.requestTimeout),t.timeout=o&&Number.isFinite(o)?o:l,this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.destroyed||(this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),s.onTimeout&&s.onTimeout(i,e,this.response))}),this.fakeXhr.timeout||t.timeout);const c="then"in(u=this.request)&&u.then instanceof Function?this.request.then(self.fetch):self.fetch(this.request);var u;const{fakeXhr:f}=this;f.readyState=f.OPENED,f.emit("readystatechange"),f._emitEvent("loadstart"),c.then((r=>{this.response=this.loader=r;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout&&s.onTimeout(i,e,this.response)}),l-(a-i.loading.start)),!r.ok){const{status:e,statusText:t}=r;throw new ps(t||"fetch, bad network response",e,r)}i.tfirst=i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=cs.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(r.headers)||i.total;let o=0;try{const e=r.headers.get("Content-Range").split("/");2===e.length&&(o=parseInt(e[1],10))}catch(e){}const{fakeXhr:c}=this;return c.readyState=c.HEADERS_RECEIVED,c.responseHeaders=r.headers,c.emit("readystatechange"),h&&"0"!==i.total?(d&&d(i.total,o),this.loadProgressively(r,i,e,h)):(c.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),n?r.arrayBuffer():"json"===e.responseType?r.json():r.text())})).then((t=>{const{response:r}=this;clearTimeout(this.requestTimeout),i.tload=i.loading.end=Math.max(performance.now(),i.loading.first);const n=t[a];n&&(i.loaded=i.total=n);const o={url:r.url,data:t,code:r.status};s.onProgress&&s.onProgress(i,e,t,r),s.onSuccess&&s.onSuccess(o,i,e,r)})).catch((t=>{if(clearTimeout(this.requestTimeout),i.aborted)return;const r=t&&t.code||0,n=t?t.message:null;s.onError&&s.onError({code:r,text:n},e,t?t.details:null,i)}))}loadProgressively(e,t,s,i){const r=e.body.getReader();let n=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>r.read().then((({value:s,done:r})=>{const{fakeXhr:u}=this;if(u.readyState!==u.LOADING&&(u.readyState=u.LOADING,u.emit("readystatechange")),s&&(n+=s.length),r){if(l.byteLength>0)if(n<=this.packetSize){const e=(0,a.h)(n);l.copy(e,0,o*this.packetSize,l.byteLength),i(e,!0)}else{const e=function(e,t){const s=e.byteLength-t,i=[];let r=t,n=Math.floor(s/c),o=s%c;for(let t=0;t<n;t++){const t=(0,a.h)(c);e.copy(t,0,r,r+c),i.push(t),r+=c}if(o>0){const t=(0,a.h)(o);e.copy(t,0,r,r+o),i.push(t)}return i}(l,o*this.packetSize);for(let t=0;t<e.length;t++)i(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:s}=this,{status:r,statusText:h,url:d}=e;return s.readyState=s.DONE,s.responseText=r,s.status=h,s.responseURL=d,s.responseType="arraybuffer",s.response=t,s.emit("readystatechange"),s._emitEvent("load"),s._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=s.length,u.emit("progress",new ProgressEvent("progress",{lengthComputable:!0,loaded:t.loaded,total:t.total})),this.callbacks.onLoaded&&this.callbacks.onLoaded({total:t.total,loaded:t.loaded,first:!h},this.context),h=!0,l=a.h.concat([l,s]),n>=this.packetSize){n-=this.packetSize;const e=(0,a.h)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,i(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function gs(e,t){return new self.Request(e.url,t)}class ps extends Error{constructor(e,t,s){super(e),this.code=t,this.details=s}}class ms extends(n()){constructor(e,t,s=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=s,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.proxied=!1,this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.forwardCanceled=!1,this.reverseCanceled=!1,this.firstReceived=!1,this.alreadyOutput=!1,this.pieceMsg={}}get isDownloading(){return this.timeReceivePiece>0}get isAlmostDeadline(){return this.rangeRequesting||this.alreadyOutput}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}get streamListeners(){return[...this.reverseStreamListeners,...this.forwardStreamListeners].length}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg,s=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let i of s){const{handler:s}=i;s(e,t,!0,"aborted by synthesizer")}this._resetStreamListeners()}_resetStreamListeners(){this.reverseStreamListeners.length=0,this.forwardStreamListeners.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,s){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:s,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:s}=this.pieceMsg,i=i=>i.filter((i=>i.peerId!==e||(i.handler(t,s,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=i(this.forwardStreamListeners),this.reverseStreamListeners=i(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let s=performance.now();e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.firstPieceTimer=setTimeout((()=>{if(this.firstReceived)return;const e=()=>{this.logger.warn(`switch to http, firstReceived ${this.firstReceived}`),this._handleTimeout(!1)};if(this.timeReceivePiece>0){const t=(this.timeReceivePiece-s)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=s+e,this._startTimer(e,t))}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.proxied&&(this.proxied=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}get hasForwardPeer(){return!!this.forwardPeer}get hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}get isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}get isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1,t),!0))}setReversePeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0,t),!0))}setPeer(e,t,s){return t?this.setReversePeer(e,s):this.setForwardPeer(e,s)}deletePeer(e){const t=e===this.reversePeer;this._detachPeer(e),t?this.reversePeer=null:this.forwardPeer=null,(this.isEmpty||this.deadline>0)&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}get hasPartialBuffer(){return this.hasForwardBuffer||this.hasReverseBuffer}get hasForwardBuffer(){return this.forwardOffset>=0}get hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments}get isForwardBufferFull(){return this.pieceMsg&&this.forwardOffset>=this.pieceMsg.attachments-1}get isReverseBufferFull(){return this.reverseOffset<=0}_cancelP2p(e=!1){const{seg_id:t,sn:s,level:i}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(s,i,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(s,i,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){this._notifyStreamListenersAbort(),this.removeAllListeners(),this.destroyed=!0,this._detachPeer(this.forwardPeer),this.forwardPeer=null,this.forwardOffset=-1,this._detachPeer(this.reversePeer),this.reversePeer=null,this.reverseOffset=1e4,this.bufArr=[],this.forwardStreamListeners=[],this.reverseStreamListeners=[],this._abortLoading()}_abortLoading(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._cancelP2p(),this.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort(),this.httpLoader=void 0)}_detachPeer(t){if(!t)return;const s=t===this.reversePeer?this.reverseEvents:this.forwardEvents;s&&s&&t.off(e.DC_PIECE_DATA,s.onPieceData).off(e.DC_PIECE,s.onPiece).off(e.DC_PIECE_NOT_FOUND,s.onPieceNotFound).off(e.DC_PIECE_ABORT,s.onPieceAbort)}_receivePacket(t,s,i,r=!0){const{seg_id:n,sn:o,level:l,size:h,ext:d}=this.pieceMsg,c=s-1;if(this.bufArr[c]?(this.logger.warn(`syn bufArr ${n} already has ${c} size ${i.byteLength}`),this.bufArr[c]=i):(r?this.p2pLoaded+=i.byteLength:this.httpLoaded+=i.byteLength,this.emit(e.SYN_PROGRESS,{total:h,loaded:this.p2pLoaded+this.httpLoaded,first:!this.firstReceived,segId:n,sn:o}),this.firstReceived=!0,this.bufArr[c]=i,t?this.reverseOffset=c:this.forwardOffset=c,this._notifyStreamListeners(t,i,c)),this.forwardOffset!==this.reverseOffset-1)return!0;this.rangeRequesting||(this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0)),clearTimeout(this.timer),this._notifyStreamListenersRemain();const u=performance.now()-this.timeStart,f=h/u;let g=a.h.concat(this.bufArr);const p=g.byteLength;if(p===h){if(this.alreadyOutput)return!1;this.alreadyOutput=!0,this._abortLoading();let t=g.buffer;const s=new X(o,n,t,this.getFromPeerId(),l,d);this.emit(e.SYN_OUTPUT,s,{speed:f,time:u,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${n} expectedSize ${h} != byteLength ${p} forward ${this.forwardOffset} reverse ${this.reverseOffset}`);for(let e=0;e<this.bufArr.length;e++)this.logger.error(`piece ${e} size ${this.bufArr[e].byteLength}`);this._onSynError(as),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:s,sn:i}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${s||i} size not match ${t} ${e}`),!1)}_setupPeer(t,s,i){const{logger:r}=this;0===this.timeStart&&(this.timeStart=performance.now()),i&&!this.pieceMsg.size&&(this.pieceMsg.size=i);const n=(e,s,i,n,a,o)=>{if(this.destroyed)return;if(!this._validateMsg(e,o.level,s))return void r.error(`onPieceData ${s||e} size ${i.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(n<this.pieceMsg.attachments&&i.byteLength!==c)return r.error(`${s} dataSn ${n} size is ${i.byteLength}`),this._onSynError(as),void this._disconnectPeers();const{reverse:l}=o;this._receivePacket(l,n,i)&&!this.waitingRemain&&!this.rangeRequesting&&this.deadline>0&&this._shouldSwitch()&&(r.warn("should switch to http"),clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._handleTimeout(!1,!1))},a=e=>{if(this.destroyed)return;const{attachments:s,size:i,sn:n,level:a,seg_id:o,ext:l={}}=e;let h=!0;(i<=999||!this._validateMsg(n,a,o))&&(r.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),h=!1),this._checkPieceSize(i)||(h=!1);const{ext:d}=this.pieceMsg;if(d&&l.hash&&d.hash&&l.hash!==d.hash&&(this.logger.warn(`syn ${o||n} hash not match ${l.hash} ${d.hash}`),h=!1),!h)return t.cancelDownload(n,a,o),void this.deletePeer(t);0===this.bufArr.length?(this.pieceMsg={...this.pieceMsg,seg_id:o,size:i,attachments:s,ext:l},this.reverseOffset=s,this.bufArr=new Array(s),this.timeReceivePiece=performance.now()):!this.pieceMsg.ext.hash&&l.hash&&(this.pieceMsg.ext.hash=l.hash)},o=e=>{this.destroyed||this.deletePeer(t)},l=()=>{this.destroyed||this.deletePeer(t)},h={onPieceData:n,onPiece:a,onPieceNotFound:o,onPieceAbort:l};s?this.reverseEvents=h:this.forwardEvents=h,t.on(e.DC_PIECE_DATA,n).once(e.DC_PIECE,a).once(e.DC_PIECE_NOT_FOUND,o).once(e.DC_PIECE_ABORT,l)}_shouldSwitch(){const e=c,t=this.pieceMsg.size-e*this.loadedPackets;return this.coordinator.shouldSwitchToHttp(t,this.deadline,this.p2pSpeed,e,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}get loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(e=!1,t=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:s,size:i,attachments:r}=this.pieceMsg;if(!i||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${s} url ${this.url}`),void this._onSynError(as);if(e&&this.timeReceivePiece>0&&r){this.logger.warn(`syn ${this.loadedPackets} of ${r} packets loaded`);const e=this.httpLoadTime>3e3?3e3:this.httpLoadTime;if(this.shouldWaitForRemain(e))return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(t){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const s=e.currentLoadSpeed(),i=t.currentLoadSpeed();return s===i?e.timeSendRequest-t.timeSendRequest:s-i})).shift();e&&e.loadtimeout()}if((this.rangeSupported||!this.hasPartialBuffer)&&this.url)return this._cancelP2p(!0),this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this._onSynError(hs)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,s=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${s}`),t>=s}minRequiredSpeed(e){let t=0;return[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(t+=e.loadedBytes())})),(this.pieceMsg.size-t)/e}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}getStreamInfo(e){const t=e?this.reverseBufList:this.forwardBufList;let s,i;return t.length<this.pieceMsg.attachments?(s=this.isFull?"WaitPartialDouble":"WaitPartialSingle",i=1):(s=this.isFull?"SynFullDouble":"SynFullSingle",i=0),{from:s,incompletes:i,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting||this.alreadyOutput)return;const{size:e,seg_id:t}=this.pieceMsg,{logger:s}=this,i=this.rangeEnd>0?this.rangeEnd-1:0;let r=this.forwardOffset;const n=performance.now();this.rangeRequesting=!0;let a=le(r,this.reverseOffset,e,this.rangeStart,i);const o=a.rangeEnd-a.rangeStart;s.info(`listeners ${this.streamListeners} continue download ${t} from ${this.url} range: ${a.rangeStart}-${a.rangeEnd}`),this.hasPartialBuffer||(a={});const l=new fs({xhrSetup:this.xhrSetup});this.httpLoader=l;let d={url:this.proxied?g(this.url,h,!0):this.url,...a};let c,u=r+1;const f={onUpdate:(e,t,i)=>{if(!this.destroyed){if(i)return s.warn("httpLoader aborted"),void(this.alreadyOutput||this._onSynError(os));if(t){const e=c/(performance.now()-n);this.coordinator.addHttpSpeed(e),this.httpLoader=void 0}this.bufArr[u]||this._receivePacket(!1,u+1,e,!1),u++}},onBodyStart:(e,i)=>{if(0===i&&s.warn(`range request fileSize ${i}`),this.destroyed)return;const{size:r}=this.pieceMsg;if(c=e,e!==r||0!==i&&i!==r){let t=!1;i>0&&i!==r?(s.error(`onBodyStart fileSize ${i} != ${r}`),t=!0):e!==o&&(s.error(`onBodyStart size ${e} != expectedSize ${o}`),t=!0),t&&"{}"!==JSON.stringify(a)&&this._onSynError(os)}else s.warn(`syn range request ${t} resp whole ts`),u=0},onError:e=>{this.destroyed||(s.error(`httpLoader error ${e.text}`),this._onSynError(os))},onTimeout:()=>{this.destroyed||(s.warn("httpLoader timeout"),this._onSynError(ls))}};l.load(d,{timeout:15e3},f)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class vs extends ms{constructor(e,s,i,r,n,a=!1,o){super(e,s,a,o),this.pieceMsg={event:t.DC_PIECE,sn:i,level:r,seg_id:n},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,s){const{sn:i,seg_id:r,attachments:n}=this.pieceMsg,a=e&&0===s||!e&&s===n-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:s}=e;s(i,r,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,s){return(!this.pieceMsg.seg_id||s===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}_onSynError(e){const{sn:s,level:i}=this.pieceMsg;this.forwardPeer&&this.forwardPeer.bitset.delete(s,i),this.reversePeer&&this.reversePeer.bitset.delete(s,i),this.emit(t.SYN_ERROR,this.pieceMsg,e)}}class ys{constructor(){this.meanHttpSpeed=0,this.loaderHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=this._cal(this.meanHttpSpeed,e)}addLoaderHttpSpeed(e,t){t&&e&&(this.loaderHttpSpeed=this._cal(this.loaderHttpSpeed,t/e))}getMeanTimeToLoaded(e){return this.loaderHttpSpeed?e/this.loaderHttpSpeed:500}shouldSwitchToHttp(e,t,s,i,r){if(this.meanHttpSpeed<=0)return!1;if(s>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*r>=e)return!1;return((r+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-s)*s<i}_cal(e,t){return.4*e+.6*t}}class Es extends ts{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new Xt(t.live||!1),this.bitCounts=new Qt,this.requestingMap=new ss,this.segmentBuilderMap=new ss,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new ys,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=10:(this.maxPrefetchCount=150,this.startCheckPeersTimer())}handshakePeer(e,t=[]){this._setupDC(e);const{asn:s,country:i}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:s,country:i},this.isMobileNet,t)}_receiveDCHave(e,t,s,i,r){this.bitset.has(e,t)||this.bitCounts.incre(e,t),r>i.currentLost&&(i.bitset.deleteOlderThan(r,t),i.currentLost=r)}_setupDC(e){super._setupDC(e),e.on(t.DC_HAVE,(t=>{if(e.bitset&&t.sn>=0){const{sn:s,level:i,complete:r,seg_id:n,size:a,curr_lost_sn:o}=t,l=r?d.COMPLETE:d.PARTIAL_FORWARD;e.bitset.add(s,i,n,l,a),this._receiveDCHave(s,i,n,e,o),e.isAvailableUrgently&&this._handleDCHave(e,s,i,n,a,l)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:s,level:i,seg_id:r,size:n,curr_lost_sn:a}=t;e.bitset.hasCompleteOr(s,i,d.PARTIAL_REVERSE)||e.bitset.add(s,i,r,d.PARTIAL_REVERSE,n),this._receiveDCHave(s,i,r,e,a),e.isAvailableUrgently&&this._handleDCHave(e,s,i,r,n,d.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:s,level:i}=t;e.bitset.has(s,i)&&(e.bitset.delete(s,i),this.bitCounts.decre(s,i))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.requestingMap.has(ce(e.sn,e.level))&&this.notifyAllPeers(e.sn,e.level,e.seg_id,e.size,e.reverse?d.PARTIAL_REVERSE:d.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:s,level:i}=t,r=ce(s,i);this.removeStreamListener(r,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:s,level:i}=t;e.bitset.delete(s,i),this.bitCounts.decre(s,i),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:s}=this,{sn:i,level:r,reverse:n}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(i));const o=()=>{this.bitset.delete(i,r),e.sendPieceNotFound(i,a,{level:r}),this._broadcastLost(i,a,r,e)},l=await this.bufMgr.getSegById(a),h=ce(i,r),d=this.requestingMap.get(h);let c=!1;d&&d.isDownloading&&(c=!0);const u=this.segmentBuilderMap.get(h);if(l)if(s.info(`found seg ${a} from bufMgr`),l.level===r){let t="SegmentStore"===this.bufMgr.name?"Disk":"Cache";l.ext.from&&l.ext.from.length<2500&&(t=`${l.ext.from}-${t}`),e.sendBuffer(l.sn,l.segId,l.data,{from:t,level:l.level,reverse:n,hash:l.ext.hash})}else o();else if(!n&&u)s.info(`peer request ${i} wait from builder, sent ${u.bufferList.length}`),w(e,u,u.pieceMsg,u.bufferList,u.source,1);else if(c){s.info(`syn had ${d.loadedPackets} packets, wait remain from upstream ${d.getFromPeerId()}`);const t={...d.pieceMsg,reverse:n},{from:i,incompletes:r,bufferList:a}=d.getStreamInfo(n);w(e,d,t,a,i,r)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new Xt(this.config.live,t.field);for(let e in t.field){const s=Number(e);if(s<0)continue;t.field[s].forEach((e=>{this.bitset.has(e,s)||this.bitCounts.incre(e,s)}))}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)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const s=Number(e),i=t[s];i&&i.forEach((e=>{this.bitCounts.decre(e,s)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,s,i){const{logger:r,config:n}=this;let a=1e3*(i-n.httpLoadTime);this.allowP2pLimit=n.httpLoadTime+1.5,r.info(`bufferedDuration ${1e3*i} remainLoadTime ${a} allowP2pLimit ${1e3*this.allowP2pLimit}`);const o=ce(e,t),l=this.requestingMap.get(o);if(l){const n=l.segId;if(n&&n!==s)return r.warn(`syn segId ${n} not match ${s}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,s,i);if(!l.shouldWaitForRemain(a)){if(r.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const i=this.peerManager.getPeersOrderByWeight();let[n,o,h]=rs(i,e,t,s);return!!this.setTargetPeersFromGroup(l,n,o,h)||(l.hasReversePeer||l.hasPartialBuffer||a>1e3*(this.allowP2pLimit+1))&&this.httpRangeSupported}return r.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,s,i)}_searchAvailablePeers(e,t,s,i){if(i<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const r=this.peerManager.getPeersOrderByWeight(),[n,a]=is(r,e,t,s);return this.targetPeers={forwardPeer:n,reversePeer:a},[n,a].some((e=>!!e))}reportTraffic(e,t,s){const{fetcher:i}=this.engine;i&&(e>0&&i.reportFlow(e),t>0&&i.reportDCTraffic(t,s))}notifyAllPeers(e,t,s,i,r=d.COMPLETE){if(!s)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:n}=this.config;if(this.bitset.has(e,t,r))return;const a=((e,t,s)=>`${e}-${t}-${s}`)(e,t,r);let o;r!==d.PARTIAL_REVERSE&&(o=r===d.COMPLETE);const l=this.currLostSN>0&&o&&n?this.currLostSN:void 0,h=this.requestingMap.get(ce(e,t));for(let c of this.getPeers())h&&h.hasPeer(c)||c.notifySet.has(a)||c.bitset.hasCompleteOr(e,t,r)||(c.sendMsgHave(e,s,{level:t,reverse:r===d.PARTIAL_REVERSE,complete:o,size:i,curr_lost_sn:l}),c.notifySet.add(a),n&&_(c.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:s}=this;if(!this.hasPeers)return;const i=t.live;if(this.fragLoading)return void e.info("loading urgently, skip prefetch");const{currentLevel:r}=s;if(0===this.bitCounts.size(r))return;if(!i&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;let n=this.peerManager.getPeersOrderByWeight();if(0===n.length)return;let a=0,{prefetchNum:o,endSN:l,startSN:h}=t;if(!i){const t=this.requestingMap.size,s=this.requestingMap.activePeers;if(s>=o)return void e.warn(`requestingMap size ${t} activePeers ${s}`);o-=s}if(this.getBufferedDuration()<this.allowP2pLimit){if(!i)return;o=1}let c=0,u=this.loadingSN+1;if(this.prefetchOnly&&(u+=2),!i)if(this.loadingSN>=l&&!this.bufMgr.overflowed)u=h;else{const e=Math.min(...n.filter((e=>e.endSN>=u)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;u<e&&(u=e)}for(;a<o&&c<this.maxPrefetchCount&&(i||!(u>l))&&!(i&&u>this.loadingSN+2);){if(this.bitset.has(u,r)){u++;continue}const t=ce(u,r),s=this.requestingMap.get(t);if(this.bitCounts.has(u,r)){if(s){for(let e of n)if(e.bitset.has(u,r)){const{state:t,segId:i,size:n}=e.bitset.getObj(u,r);if(this._trySetPeerForSyn(s,e,i,u,r,n,t))break}}else{let s=[null,null];if(i)s=is(n,u,r,void 0,!0);else for(let e of n)if(e.bitset.has(u,r)){const t=e.bitset.getState(u,r);let i;i=t===d.COMPLETE?0===m(0,1):t===d.PARTIAL_REVERSE,s[i?1:0]=e;break}if(s.some((e=>!!e))){const i=new vs(this.coordinator,this.logger,u,r,void 0,this.httpRangeSupported);this._setupSynthesizer(i),this.requestingMap.set(t,i),s.forEach(((t,s)=>{if(t&&a<o){const n=1===s,o=t.bitset.getSize(u,r);i.setPeer(t,n,o)&&(a++,t.requestDataBySN(u,!1,{level:r,reverse:n}),e.info(`request prefetch ${u} level ${r} from peer ${t.remotePeerId} downloadNum ${t.downloadNum} reverse ${n}`))}}))}}n=this.peerManager.getPeersOrderByWeight()}if(c++,u++,0===n.length)break}this.loadedPeerNum=a}onBufferManagerLost(e,t,s,i){this.currLostSN=e,s&&(this.nextLostSN=s),this.bitset.delete(e,i),this.bitCounts.delete(e,i)}onBufferManagerSegAdded(e){const{sn:t,segId:s,level:i,size:r}=e;this.notifyAllPeers(t,i,s,r),this.updateLoaded(t,i,s)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[s,i]of this.requestingMap.internalMap){const r=s.split("-"),n=Number(r[1]),a=Number(r[0]);i.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),i.deletePeer(t),this.bitCounts.decre(n,a),t.bitset.delete(n,a))}}updateLoaded(e,t,s){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,s,d.COMPLETE),this.bitCounts.delete(e,t),this.requestingMap.delete(ce(e,t)),this.config.live&&this.checkPeers())}broadcastPlaylist(e,t){if(!this.config.live)return;const s=function(e){const t=e.split("\n");let s=0,i=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){s=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&i++;return s+i-1}(t);if(!this.isMobileNet)for(let i of this.getPeers())i.sendMsgPlaylist(e,t,s);this.playlistInfo.set(e,{seq:s,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:s}=this.playlistInfo.get(e),i=()=>{for(let s of this.getPeers()){const i=s.getLatestPlaylist(e,t);if(i)return this.playlistInfo.set(e,i),this.gotPlaylist=!0,i}return null};let r=i();return!r&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await v(240),this.gotPlaylist=!1,r=i()),r}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:s}=this.engine;if(!t||t.src!==s&&0===t.currentTime){if(this.logger.info("try get video element"),t=ae(this.config.mediaElem,s),!t)return 4;this.engine.media=t}let i=function(e){let t=0,s=e.currentTime,i=e.buffered;for(let e=i.length-1;e>=0;e--)if(s>=i.start(e)&&s<=i.end(e)){t=i.end(e)-s;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return i}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear(),this.engine.removeAllListeners(t.MEDIA_REBUFFER)}clearCache(){"SegmentStore"===this.bufMgr.name?this.engine.emit(t.BM_FATAL_ERROR):this.bufMgr.clear(),this.bitset.clear()}async _handleSynOutput(e,t,s,i,r,n){if(this.logger.info(`syn output ${e} http ${t} p2p ${s} time ${i}`),!this.config.validateSegment(e,new Uint8Array(r)))return!1;if(n){const t=await k(r);if(t&&t!==n)return this.logger.warn(`${e} computedHash ${t} != hash ${n}`),!1}return!0}_handleSynError(e,t,s,i){const{logger:r,config:n}=this;r.warn(`SYN_ERROR ${t}-${s} code ${i}`),i!==as&&e.hasPartialBuffer&&s>this.loadingSN?r.warn(`syn abort ${s} with partial buffer`):this.requestingMap.delete(ce(s,t)),n.live&&this.checkPeers()}_notifySynthesizer(e,t,s,i,r,n,a=!0){const o=this.requestingMap.get(ce(s,i));o&&this._trySetPeerForSyn(o,e,t,s,i,r,n,a)}_trySetPeerForSyn(e,t,s,i,r,n,a,o=!1){const{logger:l}=this,h=e.segId;if(s&&h&&s!==h)return l.warn(`notifySynthesizer segId ${s} not match ${h}`),!1;if(e.isFull)return!0;if(e.isAlmostDeadline)return!0;if(e.isEmpty){if(e.hasForwardBuffer&&f()){if(e.setReversePeer(t,n))return c(!0,o),!0}else if(e.hasReverseBuffer&&u()&&e.setForwardPeer(t,n))return c(!1,o),!0}else if(!e.hasForwardPeer&&u()){if(e.setForwardPeer(t,n))return c(!1,o),!0}else if(!e.hasReversePeer&&f()&&e.setReversePeer(t,n))return c(!0,o),!0;function c(e,n){n?t.requestDataById(s,i,!0,{level:r,reverse:e}):t.requestDataBySN(i,!1,{level:r,reverse:e})}function u(){return a===d.PARTIAL_FORWARD||a===d.COMPLETE}function f(){return a===d.PARTIAL_REVERSE||a===d.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:s}=this.config;t||s||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,s={level:e};if(t&&!this.config.live){const{currentTime:e}=t;s.pos=Math.round(e)}return s}checkSynthesizer(e,t){const s=ce(e,t),i=this.requestingMap.get(s);i&&(0===i.streamListeners?(this.logger.info(`destroy syn ${s} without listeners`),this.requestingMap.delete(s)):this.logger.info(`keep syn ${s} with listeners`))}setupSynForLoad(e,t,s,i,r){const{forwardPeer:n,reversePeer:a}=this.targetPeers,o=ce(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(i):(l=new vs(this.coordinator,this.logger,e,t,s,this.httpRangeSupported,i),this._setupSynthesizer(l),this.requestingMap.set(o,l)),l.prefetchTimeout&&r<1e3*this.allowP2pLimit&&!n&&!a)return l.setTimeout(0);r>700&&(n&&l.setForwardPeer(n)&&n.requestDataById(s,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(s,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:r,!0)}async disconnectLoadingPeer(e,t){let s=e;if(!s){const e=await this.bufMgr.getSegById(this.loadingSegId);e&&e.fromPeerId&&(s=e.fromPeerId)}let i=!1;return s&&(this.logger.warn(`disconnect loading peer ${s}`),s.split(":").forEach((e=>{if(t&&e===t)return;i=!0;const s=this.peerManager.getPeer(e);s&&s.close(!0)}))),i}}class Ss{constructor(t,s,i,r){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=c,this.attachments=r%this.packetSize==0?r/this.packetSize:Math.floor(r/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:i,sn:t,level:s,size:r,reverse:!1},this.sink=(0,a.h)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.h.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,s){this.streamListeners.push({handler:s,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:s}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((i=>i.peerId!==e||(i.handler(t,s,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let s of this.streamListeners){const{handler:i}=s;i(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:s}=this.pieceMsg;for(let i of this.streamListeners){const{handler:r}=i;r(t,s,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const Ts=/^age:\s*[\d.]+\s*$/im;function _s(e,t,s,i){if(!e)return!1;const r=i&&i.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}const Ls=class{constructor(e){this.xhrSetup=e&&e.xhrSetup||null,this.stats=C(),this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.loader=null}destroy(){this.destroyed=!0,this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){if(this.destroyed)return;const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,t.url)})).catch((e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r(s,t.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)})).catch((e=>{this.callbacks.onError({code:s.status,text:e.message},t,s,i)})):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[t]);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,self.clearTimeout(this.requestTimeout),s.timeout=r&&Number.isFinite(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.tfirst=s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,n="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=n||t.response;if(null!=r){s.tload=s.loading.end=Math.max(self.performance.now(),s.loading.first);const n="arraybuffer"===t.responseType?r.byteLength:r.length;if(s.loaded=s.total=n,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(s,e,r,t),!this.callbacks)return;const o={url:t.responseURL,data:r,code:i};return void this.callbacks.onSuccess(o,s,e,t)}}const a=r.loadPolicy.errorRetry;_s(a,s.retry,!1,{url:e.url,data:void 0,code:i})?this.retry(a):this.callbacks.onError({code:i,text:t.statusText},e,t,s)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(_s(e,this.stats.retry,!0))this.retry(e);else{const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=function(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}(e,s.retry),s.retry++,this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Ts.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};const bs=class extends Es{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=P(t.segmentBypass)?t.segmentBypass:()=>!1,!0===t.httpStreamEnabled?this.streamEnabled=us():this.streamEnabled=!1}async handleGetMediaData(e,s){const{logger:i,engine:r,config:n}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return i.warn(`cannot get frag ${a}`),s.postMessage({action:t.SW_GET_MEDIA});r.currentLevelIndex=l.level;const{sn:h,level:d}=l,c=this.config.segmentId(String(d),h,a,o);if(r.segmentLoadCount++,this.segmentBypass(a,l.tagList))return i.info(`bypass frag ${a}`),s.postMessage({action:t.SW_GET_MEDIA});if(r.segmentLoadCount<n.startFromSegmentOffset)return this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout,!1);const u=c===this.loadingSegId;if(u&&(i.warn(`duplicate request ${c}`),this.prefetchOnly))return s.postMessage({action:t.SW_GET_MEDIA});this.loadingSN=h,r.bufMgr&&(r.bufMgr.loadingSN=h),this.loadingSegId=c;const f=await this.bufMgr.getSegById(c);if(f)return l.loaded=f.size,l.fromPeerId=f.fromPeerId,i.info(`bufMgr found seg sn ${h} segId ${c} size ${l.loaded}`),r.emit(t.FRAG_LOADED,{url:a,sn:h,level:d,segId:c,loaded:l.loaded,duration:l.duration,byP2p:!0,fromPeerId:f.fromPeerId}),this._onFragLoaded(),s.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return i.info(`prefetchOnly, skip p2p load ${c}`),this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),i.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const m=ce(h,d);if(this.resolveMap.has(h)||u){let e=this.requestingMap.get(m);if(e||u){e&&this.httpRangeSupported&&(i.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let r=setTimeout((()=>{i.info(`notify seg ${h} timeout`),r=-1,s.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{r<0||e&&e.level===d&&(clearTimeout(r),i.info(`notify seg ${e.sn}`),s.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else i.warn(`${h} is requesting, fallback`),s.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,d,c,g)){await this._loadFragByP2p(l,s,h,c,a,d,o,p)||(i.warn(`p2p timeout switch to http load ${c}`),this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,s,i,r,n,a,o=!0){const{sn:l,level:c}=e,u=ce(l,c),f=g(r,h,!0),p={},m=this.streamEnabled&&o?new fs(p):new Ls(p);let v={url:f,responseType:"arraybuffer",...b(n)};const y={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},S={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,s.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,s.postMessage({action:t.SW_GET_MEDIA})},onSuccess:async(n,a)=>{this.fragLoading=!1;const{data:o}=n;let h=a.loading.end-a.loading.start;if(this.logger.info(`HTTP loaded ${i} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(i)){const e=E(o).buffer,t=new X(l,i,e,"",c);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(u),e.segId=i,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:r,sn:l,level:c,segId:i,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),s.postMessage({action:t.SW_GET_MEDIA,data:{url:r,buffer:o}})}};if(this.streamEnabled&&o){let e;S.onBodyStart=t=>{!e&&t>0&&(this.notifyAllPeers(l,c,i,t,d.PARTIAL_FORWARD),e=new Ss(l,c,i,t),this.segmentBuilderMap.has(u)||this.segmentBuilderMap.set(u,e))},S.onUpdate=(t,s,r)=>{if(r)return this.logger.warn(`loadFragByHttp ${i} aborted`),void this.segmentBuilderMap.delete(u);e&&e.receiveBytes(t,s)}}m.load(v,y,S)}async _loadFragByP2p(e,s,i,r,n,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${i} segId ${r} level ${a}`);const d=await this.load(i,r,a,n,o,l);if(d&&d.data){const{data:o,fromPeerId:l,size:c}=d;if(h.info(`p2p loaded segId ${r} level ${a} size ${o.byteLength}`),!await this.bufMgr.hasSegOfId(r)){const e=new X(i,r,o,l,a,d.ext);h.info(`bufMgr putSeg ${i} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:n,sn:i,level:a,segId:r,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),s.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:o,size:c}}),!0}h.warn(`P2P timeout load segId ${r}`);const c=await this.bufMgr.getSegById(r);return!!c&&(this.fragLoading=!1,h.info(`already loaded seg sn ${i} segId ${r}`),s.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:c.data}}),!0)}notifySWMessage(e,s,i){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(s,i);else this.logger.warn(`unknown action ${e}`)}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(){if(!this.engine)return;const{media:e,targetDuration:t}=this.engine;!this.config.live&&e&&t&&(this.currPlaySN=Math.ceil(e.currentTime/t))}load(e,t,s,i,r,n){const{logger:a,config:o}=this;let l={...b(r),proxied:!0,url:i,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,s,t,l,n);const h=new Promise((i=>{const r={resolve:i,sn:e,level:s,segId:t};this.resolveMap.set(e,r)}));return this.targetPeers={},h}isCritical(){return this.resolveMap.has(this.loadingSN)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,s)=>{const{config:i,logger:r}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:d,time:c,http:u,p2p:f}=s,g=this.resolveMap.has(a);g&&(this.fragLoading=!1);const p=await this._handleSynOutput(n,u,f,c,o,h.hash),m=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(u,f,d),g){r.info(`receive criticalSeg seg_id ${n}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:f>0?m:void 0,ext:h})}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else{if(r.error(`segment ${n} validate failed`),g){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(ce(a,l)),this.disconnectLoadingPeer(m)}})).on(t.SYN_ERROR,((t,s)=>{const{sn:i,level:r}=t;if(this.resolveMap.has(i)){const e=this.resolveMap.get(i);this.resolveMap.delete(i),e.resolve()}this._handleSynError(e,r,i,s)}))}_handleDCHave(e,t,s,i,r,n){this._notifySynthesizer(e,i,t,s,r,n,this.resolveMap.has(t)),this.config.live&&q((()=>{this.checkPeers()}))}},Rs="2.13.0";class As extends xt{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},s=null){super(e,s),this.swSupported=self.isSecureContext,this.levels=[],this.bypassLevels=[],this.currentLevelIndex=0,this.currentSrc="",this.swVersion="",this.media=ae(this.config.mediaElem),this.workerKeepAliveInterval=null,this.fragMap=new Map,this.engineName=As.name,As.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),s&&(s.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),s.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:i,signalId:r,browserInfo:n}=this.setup();if(this.onLevelLoaded=e=>{const{config:s}=this,a=e.live;s.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...n,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${i(this.currentSrc)}|${r}[${ee.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${re.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(s.startSN=e.startSN,s.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},0===this.config.httpLoadTime&&(this.config.live?this.on(t.LEVEL_LOADED,(e=>{const{fragments:t,averagetargetduration:s,startSN:i}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,s,i)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,s)=>{this.multiBitrate=e.length>1,this.currentSrc=s,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{this.curTsUri=e;const{config:t}=this;!this.rangeTested&&t.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,t.logger&&t.logger.info(JSON.stringify({engine:this.engineName,...this.browserInfo}))),this.segmentLoadCount>=t.startFromSegmentOffset&&this.resumeTracker()},this.on(t.FRAG_LOADED,this.onFragLoaded),this.swSupported){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:s,data:i}=e.data;if(!s)return;if(s===t.SW_DEBUG){const{level:e,text:t}=i;return void(this.logger&&this.logger[e](`hls-proxy ${this.swVersion}: ${t}`))}const r=e.ports[0];if(r){if(this.logger&&this.logger.info(`engine onmessage action ${s}`),r.postMessage({action:s,pong:!0}),!this.p2pEnabled||!i)return r.postMessage({action:s});if(s===t.SW_GET_PLAYLIST)this.handleGetPlaylist(i,r);else{if(!this.scheduler)return r.postMessage({action:s});this.scheduler.notifySWMessage(s,i,r)}}else this.logger&&this.logger.error(`sender not found in action ${s}`)}}this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let s=null;const i=()=>{s||(s=setTimeout((()=>{t()}),2500))},r=()=>{null!=s&&(clearTimeout(s),s=null)};return e.addEventListener("waiting",i),e.addEventListener("playing",r),()=>{e.removeEventListener("waiting",i),e.removeEventListener("playing",r)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,s,i=!1){const{config:r,logger:n}=this,{url:a,redirectedUrl:o,text:l,ver:d}=e;return this.swVersion=d,-1===function(e,t){for(var s=e.split("."),i=t.split("."),r=0;r<Math.max(s.length,i.length);r++){var n=parseInt(s[r]||0),a=parseInt(i[r]||0);if(n<a)return-1;if(n>a)return 1}return 0}(d,Rs)?(console.warn(`hls-proxy.js version should >= ${Rs}`),s.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(R(a))>=0?(console.warn("bypass audio track"),n&&n.warn("bypass audio track"),s.postMessage({action:t.SW_GET_PLAYLIST})):(s.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:n&&n.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,R(a),o,i),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!r.live&&t()){const s=new URL(e.scope);this.pathname=s.pathname+h;const i=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;n&&(n.error(t),n.report(t,"SWKeepAlive",this.peerId,"2.17.10"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,s)=>{fetch(`${e}/keepalive/`).then((e=>{if(e.ok)return e.text();throw new Error("keepalive failed")})).then((e=>{if(""!==e.trim())throw new Error("not valid keepalive response");t()})).catch((e=>{s(e)}))}))).catch((e=>{i(e)})):i("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,s,i,r=!1){const n=s;i&&(s=i);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const o=Kt.parseLevelPlaylist(e,s);this.levels.length>0?(i=this.levels.indexOf(R(o.url)),-1===i?(this.restartP2p(),this.currentSrc=n,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&n!==this.currentSrc&&this.restartP2p(),this.currentSrc=n,this.levels=[R(s)]),this.emit(t.LEVEL_LOADED,o),a.live&&T(this.fragMap,200),o.fragments.forEach((e=>{e.level=i;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const s=e.byteRange;2===s.length&&(t=`${t}|bytes=${s[0]}-${s[1]-1}`),this.fragMap.set(t,e)})),!r&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(R(s),e)}else{const i=Kt.parseMasterPlaylist(e,s);""!==this.currentSrc&&this.restartP2p(),i.length>0&&(i.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=i.map((e=>R(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Kt.parseMasterPlaylistMedia(e,s,t).forEach((e=>{e.url&&this.bypassLevels.push(R(e.url))}))}))),this.emit(t.MANIFEST_PARSED,i,n)}this._setupSegmentId()}async handleGetPlaylist(e,s){const{config:i,logger:r,scheduler:n}=this,{url:a}=e,o=R(a);if(n&&n.playlistInfo.has(o)){const t=await n.getPlaylistFromPeer(o);if(t&&t.data){const{data:i,seq:n}=t;return r&&r.info(`got playlist from peer seq ${n}`),void this.handlePlaylist({text:i,...e},s,!0)}}try{const{text:i,redirectedUrl:n}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(i))return r&&r.warn(`not m3u8: ${i}`),s.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:i,redirectedUrl:n,...e},s)}catch(e){s.postMessage({action:t.SW_GET_PLAYLIST})}}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return S||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}return this.media=ae(t.mediaElem),this.media||e&&e.warn("no video element found"),xs.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,s)=>{const{serviceWorker:i}=navigator;i||s(e),i.getRegistration().then((i=>{i?i.unregister().then(t).catch(s):s(e)}))}))}async _init(e,t){const{logger:s,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.mediaTimer=setInterval((()=>{const e=()=>this.hlsjs&&this.hlsjs.media;if(this.media){const t=e();t&&this.media!==t&&(this.media=t),clearInterval(this.mediaTimer),this.rubufferTimer=setTimeout((()=>{this.watchRebuffering(this.media)}),15e3)}else this.media=e()||ae(i.mediaElem)}),3e3);let r=new bs(this,i);r.fragMap=this.fragMap;try{await super._init(e,r,t)}catch(e){return void(s&&s.error(e))}r.server=this.fetcher,this.scheduler=r}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.on(t.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"),clearInterval(this.mediaTimer),clearTimeout(this.rubufferTimer),this.offEventRebuffer&&this.offEventRebuffer(),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&this.tracker instanceof Mt&&(this.tracker.stopP2P(),this.tracker=null,this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED),this.removeAllListeners(t.FRAG_LOADED),clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null}destroy(){this.swSupported&&(navigator.serviceWorker.onmessage=void 0),super.destroy()}async _loadPlaylistByHttp(e){const t=g(e,h,!0),s=await fetch(t);return{text:await s.text(),redirectedUrl:s.redirected?s.url:void 0}}}const Ps=As;function ws(e,t,s="main"){return"main"!==s}function Is(e,t,s){let i,r,n;const a=performance.now();n=a,r=s?n-s.getMeanTimeToLoaded(t):a-200,i=r-100,e.trequest=i,e.tfirst=r,e.tload=n,e.loading={first:i,start:r,end:n},e.loaded=t,e.total=t}const Ds=class extends Es{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitingPeers=0,this.waitingSeg={},this.requestedSet=new Set}updatePlaySN(e){this.currPlaySN=e}load(e,t,s){const{logger:i,config:r}=this;this.context=e;const{rangeStart:n,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:d,level:c}=l;this.callbacks=s,this.criticalSeg={sn:d,level:c,segId:h};let u=e.defaultTimeout-1e3*r.httpLoadTime;const f={rangeStart:Number(n),rangeEnd:Number(a),url:o,httpLoadTime:1e3*r.httpLoadTime,xhrSetup:r.xhrSetup,segId:h,headers:Object.keys(e.headers||{}).length>0?e.headers:void 0};this.setupSynForLoad(d,c,h,f,u),this.targetPeers={}}isCritical(){return!(!this.criticalSeg||this.criticalSeg.segId!==this.loadingSegId)}addPeer(e){super.addPeer(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,s)=>{const{config:i,logger:r}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:d,time:c,http:u,p2p:f}=s,g=this.criticalSeg&&this.criticalSeg.segId===n,p=await this._handleSynOutput(n,u,f,c,o,h.hash),m=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(u,f,d),g&&this.callbacks){r.info(`receive criticalSeg seg_id ${n}`),this.criticalSeg=null;const{frag:e}=this.context;f>0&&(e.fromPeerId=m,e.loadByP2P=!0),this.callbacks.onSuccess({data:o,url:this.context.url},{},{...this.context,ext:h}),this.callbacks=void 0}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else r.error(`segment ${n} validate failed`),g&&this.callbacks.onTimeout({},this.context,null),this.requestingMap.delete(ce(a,l)),this.disconnectLoadingPeer(m)})).on(t.SYN_ERROR,((t,s)=>{const{sn:i,level:r}=t;this.criticalSeg&&this.criticalSeg.sn===i&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,r,i,s)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:s,segId:i})=>{this.criticalSeg&&this.criticalSeg.segId===i&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:s},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:s,level:i})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,s&&this.checkSynthesizer(e,i)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:s,level:i})=>{this.fragLoading=!1,s||this.checkSynthesizer(e,i)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,s,i,r,n){this._notifySynthesizer(e,i,t,s,r,n,this.criticalSeg&&this.criticalSeg.segId===i),this.config.live&&q((()=>{this.checkPeers()}))}};class Cs extends xt{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){if(super(t,e),!e)throw new TypeError("hlsjs instance is null");"serviceWorker"in navigator&&this._setupSW(),this.config.xhrSetup=e.config.xhrSetup,this.engineName=Cs.name,this._onFragLoading=this._onFragLoading.bind(this),this._onFragLoaded=this._onFragLoaded.bind(this),this._onFragChanged=this._onFragChanged.bind(this),this._onHlsError=this._onHlsError.bind(this),this._onLevelUpdated=this._onLevelUpdated.bind(this);const{channelIdMaker:s,signalId:i,browserInfo:r}=this.setup();if(P(t.interceptSegment)){class e extends this.hlsjs.constructor.DefaultConfig.loader{load(e,s,i){const{url:r}=e;if(e.frag){const e=i.onSuccess;i.onSuccess=(s,i,n,a)=>{s.data=t.interceptSegment(s.data,r),e(s,i,n,a)}}super.load(e,s,i)}}this.hlsjs.config.fLoader=e}const n=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;this._startEngine(this.hlsjs.url,h,r,s,i,l),e.off(this.HLSEvents.LEVEL_LOADED,n)};this._updateHlsEventsHandlers(),e.on(this.HLSEvents.LEVEL_LOADED,n);const a=(e,t)=>{if(!t)return;const{config:s}=this,{fragments:i,averagetargetduration:r,startSN:n}=t.details;s.httpLoadTime=this.determineHttpLoadTime(i,r,n)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,s)=>{this._setupSegmentId();const i=s.levels.length;this.multiBitrate=i>1,e.off(this.HLSEvents.MANIFEST_PARSED,o)};e.on(this.HLSEvents.MANIFEST_PARSED,o),e.on(this.HLSEvents.DESTROYING,(()=>{e.off(this.HLSEvents.LEVEL_LOADED,a),this.destroy()}))}_startEngine(e,t,s,i,r,n={}){const{config:a}=this;a.live=t,this.browserInfo={...s,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${i(e)}|${r}[${ee.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=n.startSN,a.endSN=n.endSN,o.info(`startSN ${n.startSN} endSN ${n.endSN}`)),this._init(this.channel,this.browserInfo)}async _init(e,t){const{logger:s,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const r=new Ds(this,i);try{await super._init(e,r,t)}catch(e){return void s.error(e)}this.hlsjs.config.fLoader=function(e,t,s,i){const r=i.httpStreamEnabled&&us();return class extends(n()){constructor(n){super(),this.logger=s,this.isHlsV0=i.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=r||this.isHlsV0?new fs(n):new Ls(n),this.originalLoader=n.loader,this.p2pEnabled=i.p2pEnabled,this.isLive=i.live,this.scheduler=e,this.fetcher=t,this.segmentId=i.segmentId,this.blockTypes=i.p2pBlackList,this.stats=this.httpLoader.stats||C(),this.segmentBypass=P(i.segmentBypass)?i.segmentBypass:()=>!1,this.prefetchOnly=i.prefetchOnly,this.startFromSegmentOffset=i.startFromSegmentOffset,this.interceptSegment=P(i.interceptSegment)?i.interceptSegment:e=>e}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,s){const{logger:i,scheduler:r}=this,{url:n,frag:a}=e;this.isHlsV0||(a.stats=this.stats);const{level:o,sn:l,type:h,tagList:d}=a;let c=a.segId;if(!c){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),c=a.segId=this.segmentId(String(o),l,n,t)}const u=()=>(a.loadByHTTP=!0,new this.originalLoader(t).load(e,t,s));if(!n||!Number.isInteger(l)||ws(0,this.blockTypes,h)||this.segmentBypass(n,d))return i.info(`HTTP load blockType ${n}`),u();if(this.fetcher.increMediaRequests(),this.isLive&&r.requestedSet.has(c))return i.warn(`HTTP load duplicated ${n}`),u();if(r.engine.segmentLoadCount<this.startFromSegmentOffset)return u();t.maxRetry=2;const f=r.getBufferedDuration(),g=await this.bufMgr.getSegById(c);if(this.p2pEnabled&&g){i.info(`bufMgr found seg sn ${l} segId ${c} level ${o} size ${g.size}`);let t=E(g.data).buffer,h={url:e.url,data:t};return Is(this.stats,g.size,r.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void q((()=>{!this.isHlsV0&&s.onProgress&&s.onProgress(this.stats,e,h.data),h.data=this.interceptSegment(h.data,n),s.onSuccess(h,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&r.hasAndSetTargetPeer(l,o,c,f)?this.loadFragByP2p(e,t,s,c,f):(i.info(`fragLoader load ${c} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,s,c))}loadFragByHttp(e,t,s,i){const{logger:n,scheduler:a}=this,{segmentBuilderMap:o}=a,l=e.frag,{sn:h,level:c}=l,u=ce(h,c);if(r){let e;s.onUpdate=(t,s,r)=>{if(r)return n.warn(`loadFragByHttp ${i} aborted`),void o.delete(u);e&&e.receiveBytes(t,s)},s.onBodyStart=t=>{!e&&t>0&&(e=new Ss(h,c,i,t),o.has(u)||o.set(u,e),a.notifyAllPeers(h,c,i,t,d.PARTIAL_FORWARD))}}const f=s.onSuccess;s.onSuccess=async(e,t,s)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:r}=e;let d=t.tload-t.trequest;if(n.info(`HTTP loaded ${i} time ${d} speed ${t.total/d}`),l.loaded=t.total,!await this.bufMgr.hasSegOfId(i)){const e=E(r).buffer,t=new X(h,i,e,this.fetcher.peerId,c);await this.bufMgr.putSeg(t)}o.delete(u),this.fetcher.reportFlow(t.total),e.data=this.interceptSegment(e.data,s.url),f(e,t,s)},e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,s)}loadFragByP2p(t,s,i,r,n){const{logger:a}=this,o=t.frag;let l;l=s.loadPolicy?s.loadPolicy.maxTimeToFirstByteMs:s.timeout,(!l||l>1e3*n)&&(l=1e3*n),t.defaultTimeout=l,this.scheduler.load(t,s,i);const h=i.onSuccess,d=i.onTimeout;i.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),i.onSuccess=h,this.loadFragByHttp(t,s,i,r),i.onTimeout=d},i.onSuccess=async(t,s,n)=>{const{data:l}=t;if(Is(s=this.stats,l.byteLength,e.coordinator),!await this.bufMgr.hasSegOfId(r)){const e=E(l).buffer,t=new X(o.sn,r,e,o.fromPeerId||this.fetcher.peerId,o.level,n.ext);await this.bufMgr.putSeg(t)}o.loadByP2P||this.fetcher.reportFlow(s.total),o.loaded=s.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${r}`),!this.isHlsV0&&i.onProgress&&i.onProgress(s,n,l),t.data=this.interceptSegment(t.data,n.url),h(t,s,n)}}}}(r,this.fetcher,s,i),i.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,s){return class extends(n()){constructor(i){super(),this.logger=t,this.xhrLoader=new i.loader(i),this.p2pEnabled=s.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||C()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,s){const{logger:i}=this,{url:r}=e,n=R(r),a=s.onSuccess;if(s.onSuccess=(e,t,s)=>{this.scheduler&&!s.loadedByPeer&&this.scheduler.broadcastPlaylist(n,e.data),a(e,t,s)},this.scheduler&&this.scheduler.playlistInfo.has(n)){const t=await this.scheduler.getPlaylistFromPeer(n);if(t&&t.data){const{data:n,seq:a}=t;i.info(`got playlist from peer seq ${a}`),Is(this.stats,n.length);let o={url:r,data:n};return e.loadedByPeer=!0,void q((()=>{s.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,s)}}}(r,s,i))}_onFragLoading(e,s){const i=s.frag;let{sn:r,level:n,segId:a}=i;if(!ws(i.url,this.config.p2pBlackList,i.type)&&Number.isInteger(r)){if(this.logger&&this.logger.info("loading frag "+r),this.bufMgr&&(this.bufMgr.loadingSN=r),!a){let e;i._byteRange&&(e="bytes="+i._byteRange[0]+"-"+i._byteRange[1]);let t=i.url;this._setupSegmentId(),a=i.segId=this.config.segmentId(String(n),i.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:r,segId:a,byHttp:i.loadByHTTP,level:n})}}_onLevelUpdated(e,t){const{details:s}=t,{hlsjs:i,config:r}=this,{targetduration:n,live:a,fragments:o}=s,l=o.length;if(a&&i&&"main"===o[0].type&&!(l<=4)&&(r.isHlsV0||!i.userConfig.liveSyncDuration&&!i.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;i.config.liveSyncDurationCount!==e&&(i.config.liveSyncDurationCount=e)}}_onFragLoaded(e,s){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:i}=s;this.curTsUri=i.url;const{sn:r,segId:n,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:d,url:c}=i,{config:u,logger:f}=this;this.tracker&&this.tracker.scheduler&&(_(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(n)),ws(i.url,u.p2pBlackList,i.type)||(this.bufMgr&&this.bufMgr.loadingSN>=0&&this.emit(t.FRAG_LOADED,{url:c,sn:r,level:l,segId:n,loaded:a,duration:o,byP2p:!!d,fromPeerId:h}),!this.rangeTested&&u.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,f&&f.info(JSON.stringify({engine:this.engineName,hlsjs:this.hlsjsVersion,...this.browserInfo})))),this.segmentLoadCount>=u.startFromSegmentOffset&&this.resumeTracker()}_onFragChanged(e,s){const{frag:i}=s;if(!ws(i.url,this.config.p2pBlackList,i.type)){this.logger&&this.logger.info("frag changed: "+i.sn);const{sn:e,duration:s}=i;this.emit(t.FRAG_CHANGED,{sn:e,duration:s})}}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.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}_updateHlsEventsHandlers(e=!1){const t=this.hlsjs;if(!t)return;const s=e?"off":"on";t[s](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[s](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[s](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[s](this.HLSEvents.ERROR,this._onHlsError),t[s](this.HLSEvents.LEVEL_UPDATED,this._onLevelUpdated)}destroy(){this._updateHlsEventsHandlers(!0),super.destroy()}_setupSW(){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:t}=e.data,s=e.ports[0];if(s)return s.postMessage({action:t,pong:!0}),s.postMessage({action:t,data:{bypass:!0}})}}}const ks=Cs;class Ms{static get Events(){return t}static get TrackerZone(){return re.TrackerZone}static isSupported(){return re.isSupported()&&(ne()||Ps.isServiceWorkerSupported())}static isServiceWorkerSupported(){return Ps.isServiceWorkerSupported()}static isMSESupported(){return ne()}static getBrowser(){return J().getBrowser()}static get ServiceWorkerEngine(){return Ps}static get HlsjsEngine(){return ks}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return Ms.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:s}={}){const{serviceWorker:i}=navigator;return!i||s?Promise.resolve():i.getRegistration().then((s=>s||Promise.race([i.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,s)=>{const i=e.installing||e.waiting||e.active,r=()=>"activated"===i.state&&(i.removeEventListener("statechange",r),t(e),!0);r()||i.addEventListener("statechange",r)}))}(e))).catch((()=>{Promise.resolve()})),v(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const s=()=>{this._realEngine=new ks(t,e)},i=()=>{this._realEngine=new Ps(e,t)};"1"!==f("_sw")?e.proxyFirst&&t?Ps.isServiceWorkerSupported()?i():s():!e.proxyOnly&&ne()&&t?s():i():i()}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(){return this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}async registerServiceWorker(){return P(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return P(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return re.version}}Ms.version=re.version,Ms.protocolVersion=ee.VERSION,"object"==typeof self&&(self.P2PEngineHls=Ms);const xs=Ms,Os=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Fs=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=Ns},Ns=Number.MAX_SAFE_INTEGER||9007199254740991;let $s=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Bs=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",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.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),Us=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var Gs="manifest",Hs="level",Vs="audioTrack",Ws="subtitleTrack",qs="main",js="audio",zs="subtitle";class Ks{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Ys{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ks(e),this.fast_=new Ks(t),this.defaultTTFB_=i,this.ttfb_=new Ks(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new Ks(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Ks(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ks(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const s=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Xs(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function Qs(){return Qs=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},Qs.apply(null,arguments)}function Js(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,i)}return s}function Zs(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Js(Object(s),!0).forEach((function(t){Xs(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Js(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}class ei{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=ti,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const ti=function(){},si={trace:ti,debug:ti,log:ti,warn:ti,info:ti,error:ti};function ii(){return Qs({},si)}function ri(e,t,s){return t[e]?t[e].bind(t):function(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):ti}(e,s)}const ni=ii();const ai=ni;function oi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var li,hi;var di=hi?li:(hi=1,li={}),ci=oi(di);function ui(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function fi(e,t=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(e);if(t){const e=s.indexOf("\0");return-1!==e?s.substring(0,e):s}return s.replace(/\0/g,"")}const s=e.length;let i,r,n,a="",o=0;for(;o<s;){if(i=e[o++],0===i&&t)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&n)}}return a}function gi(e){let t="";for(let s=0;s<e.length;s++){let i=e[s].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function pi(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var mi,vi={exports:{}};var yi=(mi||(mi=1,function(e,t){!function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=a.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=a.normalizePath(r.path),a.buildURLFromParts(r)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(c)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=s.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=s.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()}(vi)),vi.exports);class Ei{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Si="audio",Ti="video",_i="audiovideo";class Li{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const s=Pi(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;i=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Si]:null,[Ti]:null,[_i]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new Ei),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=yi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Si]=null,e[Ti]=null,e[_i]=null}}function bi(e){return"initSegment"!==e.sn}class Ri extends Li{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(Os(e)&&Os(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const s=this._decryptdata=t[e[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=Os(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),s=e.length;if(s>1||1===s&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){Os(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return bi(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class Ai extends Li{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function Pi(e,t){const s=Object.getPrototypeOf(e);if(s){const e=Object.getOwnPropertyDescriptor(s,t);return e||Pi(s,t)}}const wi=Math.pow(2,32)-1,Ii=[].push,Di={video:1,audio:2,id3:3,text:4};function Ci(e){return String.fromCharCode.apply(null,e)}function ki(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function Mi(e,t){const s=Oi(e,t);return s<0?4294967296+s:s}function xi(e,t){let s=Mi(e,t);return s*=Math.pow(2,32),s+=Mi(e,t+4),s}function Oi(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Fi(e,t){const s=[];if(!t.length)return s;const i=e.byteLength;for(let r=0;r<i;){const n=Mi(e,r),a=n>1?r+n:i;if(Ci(e.subarray(r+4,r+8))===t[0])if(1===t.length)s.push(e.subarray(r+8,a));else{const i=Fi(e.subarray(r+8,a),t.slice(1));i.length&&Ii.apply(s,i)}r=a}return s}function Ni(e){const t=[],s=e[0];let i=8;const r=Mi(e,i);i+=4;let n=0,a=0;0===s?(n=Mi(e,i),a=Mi(e,i+4),i+=8):(n=xi(e,i),a=xi(e,i+8),i+=16),i+=2;let o=e.length+a;const l=ki(e,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=Mi(e,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return ai.warn("SIDX has hierarchical references (not supported)"),null;const l=Mi(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:t}}function $i(e){const t=[],s=Fi(e,["moov","trak"]);for(let e=0;e<s.length;e++){const i=s[e],r=Fi(i,["tkhd"])[0];if(r){let e=r[0];const s=Mi(r,0===e?12:20),n=Fi(i,["mdia","mdhd"])[0];if(n){e=n[0];const r=Mi(n,0===e?12:20),a=Fi(i,["mdia","hdlr"])[0];if(a){const e=Ci(a.subarray(8,12)),n={soun:Si,vide:Ti}[e],o=Bi(Fi(i,["mdia","minf","stbl","stsd"])[0]);n?(t[s]={timescale:r,type:n,stsd:o},t[n]=Zs({timescale:r,id:s},o)):t[s]={timescale:r,type:e,stsd:o}}}}}return Fi(e,["moov","mvex","trex"]).forEach((e=>{const s=Mi(e,4),i=t[s];i&&(i.default={duration:Mi(e,12),flags:Mi(e,20)})})),t}function Bi(e){const t=e.subarray(8),s=t.subarray(86),i=Ci(t.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const e=Fi(t,[i])[0];Fi(e.subarray("enca"===i?28:78),["sinf"]).forEach((e=>{const t=Fi(e,["schm"])[0];if(t){const s=Ci(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=Fi(e,["frma"])[0];t&&(n=Ci(t))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=Fi(s,["avcC"])[0];e&&e.length>3&&(n+="."+Hi(e[1])+Hi(e[2])+Hi(e[3]),r=Ui("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const e=Fi(t,[i])[0],s=Fi(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=Gi(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=Gi(s,e);const i=s[e++];if(64!==i)break;if(n+="."+Hi(i),e+=12,5!==s[e++])break;e=Gi(s,e);const r=s[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=Fi(s,["hvcC"])[0];if(e&&e.length>12){const t=e[1],s=["","A","B","C"][t>>6],i=31&t,r=Mi(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+s+i,n+="."+function(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];if(t||h){h="."+t.toString(16).toUpperCase()+h}}n+=h}r=Ui("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Ui(n,s)||n;break;case"vp09":{const e=Fi(s,["vpcC"])[0];if(e&&e.length>6){const t=e[4],s=e[5],i=e[6]>>4&15;n+="."+Vi(t)+"."+Vi(s)+"."+Vi(i)}break}case"av01":{const e=Fi(s,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,i=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,d=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,p=1,m=1,v=0;n+="."+t+"."+Vi(i)+a+"."+Vi(h)+"."+d+"."+c+u+f+"."+Vi(g)+"."+Vi(p)+"."+Vi(m)+"."+v,r=Ui("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function Ui(e,t){const s=Fi(t,["dvvC"]),i=s.length?s[0]:Fi(t,["dvcC"])[0];if(i){const t=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return e+"."+Vi(t)+"."+Vi(s)}}function Gi(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function Hi(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Vi(e){return(e<10?"0":"")+e}function Wi(e,t){Fi(e,["moov","trak"]).forEach((e=>{const s=Fi(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=Fi(i,["enca"]);const n=r.length>0;n||(r=Fi(i,["encv"])),r.forEach((e=>{Fi(n?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const s=function(e){const t=Fi(e,["schm"])[0];if(t){const s=Ci(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=Fi(e,["schi","tenc"])[0];if(t)return t}}}(e);s&&t(s,n)}))}))}))}function qi(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function ji(e,t){const s=[],i=t.samples,r=t.timescale,n=t.id;let a=!1;return Fi(i,["moof"]).map((o=>{const l=o.byteOffset-8;Fi(o,["traf"]).map((o=>{const h=Fi(o,["tfdt"]).map((e=>{const t=e[0];let s=Mi(e,4);return 1===t&&(s*=Math.pow(2,32),s+=Mi(e,8)),s/r}))[0];return void 0!==h&&(e=h),Fi(o,["tfhd"]).map((h=>{const d=Mi(h,4),c=16777215&Mi(h,0);let u=0;const f=!!(16&c);let g=0;const p=!!(32&c);let m=8;d===n&&(!!(1&c)&&(m+=8),!!(2&c)&&(m+=4),!!(8&c)&&(u=Mi(h,m),m+=4),f&&(g=Mi(h,m),m+=4),p&&(m+=4),"video"===t.type&&(a=zi(t.codec)),Fi(o,["trun"]).map((n=>{const o=n[0],h=16777215&Mi(n,0),d=!!(1&h);let c=0;const f=!!(4&h),p=!!(256&h);let m=0;const v=!!(512&h);let y=0;const E=!!(1024&h),S=!!(2048&h);let T=0;const _=Mi(n,4);let L=8;d&&(c=Mi(n,L),L+=4),f&&(L+=4);let b=c+l;for(let l=0;l<_;l++){if(p?(m=Mi(n,L),L+=4):m=u,v?(y=Mi(n,L),L+=4):y=g,E&&(L+=4),S&&(T=0===o?Mi(n,L):Oi(n,L),L+=4),t.type===Ti){let t=0;for(;t<y;){const n=Mi(i,b);if(b+=4,Ki(a,i[b])){Yi(i.subarray(b,b+n),a?2:1,e+T/r,s)}b+=n,t+=n+4}}e+=m/r}})))}))}))})),s}function zi(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Ki(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Yi(e,t,s,i){const r=Xi(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){ai.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=ki(r,t);if(t+=2,49===e){const e=Mi(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=r[t++]}i.push({type:e,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let s=0;s<16;s++){const i=r[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];i.push({payloadType:a,pts:s,uuid:e.join(""),userData:fi(l),userDataBytes:l})}}}function Xi(e){const t=e.byteLength,s=[];let i=1;for(;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return e;const r=t-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=e[a];return n}const Qi=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ji={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Zi(e,t){const s=Ji[t];return!!s&&!!s[e.slice(0,4)]}function er(e,t,s=!0){return!e.split(",").some((e=>!tr(e,t,s)))}function tr(e,t,s=!0){var i;const r=ui(s);return null!=(i=null==r?void 0:r.isTypeSupported(sr(e,t)))&&i}function sr(e,t){return`${t}/mp4;codecs=${e}`}function ir(e){if(e){const t=e.substring(0,4);return Ji.video[t]}return 2}function rr(e){const t=Qi();return e.split(",").reduce(((e,s)=>{const i=t&&zi(s)?9:Ji.video[s];return i?(2*i+e)/(e?3:2):(Ji.audio[s]+e)/(e?2:1)}),0)}const nr={};const ar=/flac|opus|mp4a\.40\.34/i;function or(e,t=!0){return e.replace(ar,(e=>function(e,t=!0){if(nr[e])return nr[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<s.length;r++){var i;if(tr(s[r],"audio",t))return nr[e]=s[r],s[r];if("mp3"===s[r]&&null!=(i=ui(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)))}function lr(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(hr(e,"audio")||hr(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function hr(e,t){return Zi(e,t)&&tr(e,t)}function dr(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function cr(e){const t=ui(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function ur(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const fr=["NONE","TYPE-0","TYPE-1",null];const gr=["SDR","PQ","HLG"];var pr="",mr="YES",vr="v2";function yr(e){const{canSkipUntil:t,canSkipDateRanges:s,age:i}=e;return t&&i<t/2?s?vr:mr:pr}class Er{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Sr{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=null==(t=e.supplemental)?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Tr(this._audioGroups,e)}hasSubtitleGroup(e){return Tr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Tr(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function _r(e,t){let s=!1,i=[];if(e&&(s="SDR"!==e,i=[e]),t){i=t.allowedVideoRanges||gr.slice(0);const e="SDR"!==i.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const Lr=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(s,i)=>{if(e&&(i=e(s,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}})(t));function br(e,t){ai.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Rr(e){return e.reduce(((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ar(e,t){var s;return!!e&&e!==(null==(s=t.loadLevelObj)?void 0:s.uri)}const Pr=function(e,t){let s=0,i=e.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=e[r];const a=t(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function wr(e,t,s=0,i=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const i=e.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Ir(s,i,n)||function(e,t,s){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),s);return e.start<=i}return!1}(n,e,Math.min(r,i))))return n;const a=Pr(t,Ir.bind(null,s,i));return!a||a===e&&n?n:a}function Ir(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=e?1:s.start-i>e&&s.start?-1:0}function Dr(e,t,s){const i=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>e}function Cr(e){switch(e.details){case Bs.FRAG_LOAD_TIMEOUT:case Bs.KEY_LOAD_TIMEOUT:case Bs.LEVEL_LOAD_TIMEOUT:case Bs.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function kr(e){return e.details.startsWith("key")}function Mr(e){return kr(e)&&!!e.frag&&!e.frag.decryptdata}function xr(e,t){const s=Cr(t);return e.default[(s?"timeout":"error")+"Retry"]}function Or(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function Fr(e){return Zs(Zs({},e),{errorRetry:null,timeoutRetry:null})}function Nr(e,t,s,i){if(!e)return!1;const r=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return $r(e)||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}function $r(e){return 0===e&&!1===navigator.onLine}var Br=0,Ur=2,Gr=3,Hr=5,Vr=0,Wr=1,qr=2,jr=4;function zr(e){const t={action:Br,flags:Vr};return e&&(t.resolved=!0),t}const Kr=/^(\d+)x(\d+)$/,Yr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Xr{constructor(e,t){"string"==typeof e&&(e=Xr.parseAttrList(e,t)),Qs(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}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 s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}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])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce(((e,t)=>(e[t.toLowerCase()]=!0,e)),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=Kr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(Yr.lastIndex=0;null!==(s=Yr.exec(e));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o));else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ai.warn(`${e}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function Qr(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Jr{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){ai.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Qs(new Xr({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);Os(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(ai.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Os(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Os(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class Zr{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some((t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)}))}get hasProgramDateTime(){return!!this.fragments.length&&Os(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function en(e,t){return e.length===t.length&&!e.some(((e,s)=>e!==t[s]))}function tn(e,t){return!e&&!t||!(!e||!t)&&en(e,t)}var sn=0,rn=1;function nn(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function an(e){switch(e){case"AES-128":case"AES-256":return sn;case"AES-256-CTR":return rn;default:throw new Error(`invalid full segment method ${e}`)}}let on={};class ln{static clearKeyUriToKeyIdMap(){on={}}static setKeyIdForUri(e,t){on[e]=t}static addKeyIdForUri(e){const t=Object.keys(on).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),on[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!nn(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(pi(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&en(e.keyFormatVersions,this.keyFormatVersions)&&tn(e.iv,this.iv)&&tn(e.keyId,this.keyId)}isSupported(){if(this.method){if(nn(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(nn(this.method)){let t=this.iv;t||("number"!=typeof e&&(ai.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}(e));return new ln(this.method,this.uri,"identity",this.keyFormatVersions,t)}return this}}const hn=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,dn=/#EXT-X-MEDIA:(.*)/g,cn=/^#EXT(?:INF|-X-TARGETDURATION):/m,un=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),fn=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class gn{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return yi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return cn.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},i=[];if(hn.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let r;for(;null!=(r=hn.exec(e));)if(r[1]){var n;const e=new Xr(r[1],s),a=r[2],o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:gn.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),En(e.CODECS,o);const h=e["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},En(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),s.levels.push(o)}else if(r[3]){const e=r[3],i=r[4];switch(e){case"SESSION-DATA":{const e=new Xr(i,s),t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{const e=vn(i,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):ai.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const e=new Xr(i,s);s.contentSteering={uri:gn.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=yn(i)}}const a=i.length>0&&i.length<s.levels.length;return s.levels=a?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,a={AUDIO:n.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(dn.lastIndex=0;null!==(i=dn.exec(e));){const e=new Xr(i[1],s),n=e.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?gn.resolve(e.URI,t):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const e=gn.findGroup(s,f.groupId)||s[0];Sn(f,e,"audioCodec"),Sn(f,e,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var a;const o={url:t},l=new Zr(t),h=l.fragments,d=[];let c,u,f,g,p=null,m=0,v=0,y=0,E=0,S=0,T=null,_=new Ri(i,o),L=-1,b=!1,R=null;if(un.lastIndex=0,l.m3u8=e,l.hasVariableRefs=!1,"#EXTM3U"!==(null==(a=un.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=un.exec(e));){b&&(b=!1,_=new Ri(i,o),_.playlistOffset=y,_.setStart(y),_.sn=m,_.cc=E,S&&(_.bitrate=S),_.level=s,p&&(_.initSegment=p,p.rawProgramDateTime&&(_.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),R&&(_.setByteRange(R),R=null)));const e=c[1];if(e){_.duration=parseFloat(e);const t=(" "+c[2]).slice(1);_.title=t||null,_.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(Os(_.duration)){_.playlistOffset=y,_.setStart(y),f&&Ln(_,f,l),_.sn=m,_.level=s,_.cc=E,h.push(_);const e=(" "+c[3]).slice(1);_.relurl=e,Tn(_,T,d),T=_,y+=_.duration,m++,v=0,b=!0}}else{if(c=c[0].match(fn),!c){ai.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),n=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":T?_.setByteRange(r,T):_.setByteRange(r);break;case"PROGRAM-DATE-TIME":_.rawProgramDateTime=r,_.tagList.push(["PROGRAM-DATE-TIME",r]),-1===L&&(L=h.length);break;case"PLAYLIST-TYPE":l.type&&bn(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?bn(l,e,c):h.length>0&&Rn(l,e,c),m=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&bn(l,e,c);const t=new Xr(r,l),s=t.decimalInteger("SKIPPED-SEGMENTS");if(Os(s)){l.skippedSegments+=s;for(let e=s;e--;)h.push(null);m+=s}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&bn(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&bn(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"ENDLIST":l.live||bn(l,e,c),l.live=!1;break;case"#":(r||n)&&_.tagList.push(n?[r,n]:[r]);break;case"DISCONTINUITY":E++,_.tagList.push(["DIS"]);break;case"GAP":_.gap=!0,_.tagList.push([e]);break;case"BITRATE":_.tagList.push([e,r]),S=1e3*parseInt(r),Os(S)?_.bitrate=S:S=0;break;case"DATERANGE":{const e=new Xr(r,l),t=new Jr(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:ai.warn(`Ignoring invalid DATERANGE tag: "${r}"`),_.tagList.push(["EXT-X-DATERANGE",r]);break}case"DISCONTINUITY-SEQUENCE":0!==l.startCC?bn(l,e,c):h.length>0&&Rn(l,e,c),l.startCC=E=parseInt(r);break;case"KEY":{const e=vn(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=Qs({},f)),f[e.keyFormat]=e)}else ai.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}" (light build)`);break}case"START":l.startTimeOffset=yn(r);break;case"MAP":{const e=new Xr(r,l);if(_.duration){const t=new Ri(i,o);_n(t,e,s,f),p=t,_.initSegment=p,p.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=p.rawProgramDateTime)}else{const t=_.byteRangeEndOffset;if(t){const e=_.byteRangeStartOffset;R=`${t-e}@${e}`}else R=null;_n(_,e,s,f),p=_,b=!0}p.cc=E;break}case"SERVER-CONTROL":g&&bn(l,e,c),g=new Xr(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&bn(l,e,c);const t=new Xr(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,s=v++,i=new Xr(r,l),n=new Ai(i,_,o,s,t);e.push(n),_.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new Xr(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Xr(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:ai.warn(`line parsed but not handled: ${c}`)}}}T&&!T.relurl?(h.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(Tn(_,T,d),_.cc=E,l.fragmentHint=_,f&&Ln(_,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const A=h.length,P=h[0],w=h[A-1];if(y+=l.skippedSegments*l.targetduration,y>0&&A&&w){l.averagetargetduration=y/A;const e=w.sn;l.endSN="initSegment"!==e?e:0,l.live||(w.endList=!0),L>0&&(!function(e,t){let s=e[t];for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(h,L),P&&d.unshift(P))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&P&&pn(d,l),l.endCC=E,l}}function pn(e,t){let s=e.length;if(!s){if(!t.hasProgramDateTime)return;{const i=t.fragments[t.fragments.length-1];e.push(i),s++}}const i=e[s-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=e[i])?void 0:a.sn)<t.startSN)break;const s=mn(t,h,e,i,r);if(-1!==s){l.tagAnchor=t.fragments[s].ref;break}}}}function mn(e,t,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(t>=o||0===i){var a;if(t<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>s.length){for(let a=(s[i+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function vn(e,t,s){var i,r;const n=new Xr(e,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&ai.error(`Invalid IV: ${n.IV}`);const c=o?gn.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ln(a,c,d,u,l,n.KEYID)}function yn(e){const t=new Xr(e).decimalFloatingPoint("TIME-OFFSET");return Os(t)?t:null}function En(e,t){let s=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const i=s.filter((t=>Zi(t,e)));i.length&&(t[`${e}Codec`]=i.map((e=>e.split("/")[0])).join(","),s=s.filter((e=>-1===i.indexOf(e))))})),t.unknownCodecs=s}function Sn(e,t,s){const i=t[s];i&&(e[s]=i)}function Tn(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function _n(e,t,s,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Ln(e,t,s){e.levelkeys=t;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||i.push(e)}function bn(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function Rn(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function An(e,t){const s=t.startPTS;if(Os(s)){let i,r=0;t.sn>e.sn?(r=s-e.start,i=e):(r=e.start-s,i=t),i.duration!==r&&i.setDuration(r)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Pn(e,t,s,i,r,n,a){i-s<=0&&(a.warn("Fragment should have a positive duration",t),i=s+t.duration,n=r+t.duration);let o=s,l=i;const h=t.startPTS,d=t.endPTS;if(Os(h)){const c=Math.abs(h-s);e&&c>e.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${t.level} ${e.url}`):Os(t.deltaPTS)?t.deltaPTS=Math.max(c,t.deltaPTS):t.deltaPTS=c,o=Math.max(s,h),s=Math.min(s,h),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,l=Math.min(i,d),i=Math.max(i,d),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const c=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(i-t.start),t.startPTS=s,t.maxStartPTS=o,t.startDTS=r,t.endPTS=i,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const g=u-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)An(p[f],p[f-1]);for(f=g;f<p.length-1;f++)An(p[f],p[f+1]);return e.fragmentHint&&An(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function wn(e,t,s){if(e===t)return;let i=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){i=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,s){const i=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let h=r;h<=n;h++){const r=l[a+h];let n=o[h];if(i&&!n&&r&&(n=t.fragments[h]=r),r&&n){s(r,n,h,o);const i=r.relurl,a=n.relurl;if(i&&Fn(i,a))return void(t.playlistParsingError=In(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=In(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,((e,s,r,a)=>{if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){const i=e.cc-s.cc;for(let e=r;e<a.length;e++)a[e].cc+=i;t.endCC=a[a.length-1].cc}Os(e.startPTS)&&Os(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(n=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,i=e.initSegment)}));const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)})),t.skippedSegments){if(t.deltaUpdateFailed=a.some((e=>!e)),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,s){const{dateRanges:i,recentlyRemovedDateranges:r}=t,n=Qs({},e);r&&r.forEach((e=>{delete n[e]}));const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach((e=>{const t=n[e],r=new Jr(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Lr(i[e].attr)}"`)})),n}(e.dateRanges,t,s));const i=e.fragments.filter((e=>e.rawProgramDateTime));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&Tn(o[e],o[e-1],i);pn(i,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const s=kn(e,t.startSN-1);t.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}!function(e,t,s){if(e&&t){let i=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),n?Pn(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):Dn(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function In(e,t,s,i,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function Dn(e,t,s=!0){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&s)a=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}!function(e,t){if(t){const s=e.fragments;for(let i=e.skippedSegments;i<s.length;i++)s[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,a)}function Cn(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const i=e.fragments,r=4;if(i.length&&s*r>t){const e=1e3*i[i.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function kn(e,t,s){if(!e)return null;let i=e.fragments[t-e.startSN];return i||(i=e.fragmentHint,i&&i.sn===t?i:t<e.startSN&&s&&s.sn===t?s:null)}function Mn(e,t,s){return e?xn(e.partList,t,s):null}function xn(e,t,s){if(e)for(let i=e.length;i--;){const r=e[i];if(r.index===s&&r.fragment.sn===t)return r}return null}function On(e){e.forEach(((e,t)=>{var s;null==(s=e.details)||s.fragments.forEach((e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function Fn(e,t){return!(e===t||!t)&&Nn(e)!==Nn(t)}function Nn(e){return e.replace(/\?[^?]*$/,"")}class $n extends ei{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=null==t?void 0:t.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=s;break}a===e.substring(0,a.length)&&(r=s)}if(-1!==r){const e=i[r],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&yr(s);return new Er(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const e=Math.max(o||0,0);i.appliedTimelineOffset=e,i.fragments.forEach((t=>{t.setStart(t.playlistOffset+e)}))}if(i.live||null!=s&&s.live){const o="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){wn(s,i,this);const e=i.playlistParsingError;if(e){this.warn(e);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void s.trigger(Us.ERROR,{type:$s.NETWORK_ERROR,details:Bs.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=Cn(i,1e3*(i.edge-d));if(i.requestScheduled+c<n?i.requestScheduled=n:i.requestScheduled+=c,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let u,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,r=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,h=r===a;-1!==l?h?(f=a+1,g=e?0:l):(f=r,g=e?l+1:i.maxPartIndex):f=a+1;const d=i.age,c=d+i.ageHeader;let p=Math.min(c-i.partTarget,1.5*i.targetduration);if(p>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${p} with playlist age: ${i.age}`),p=0;else{const e=Math.floor(p/i.targetduration);if(f+=e,void 0!==g){g+=Math.round(p%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${p} skip sn ${e} to part ${g}`)}i.tuneInGoal=p}if(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g),e||!h)return i.requestScheduled=n,void this.loadingPlaylist(o,u)}else(i.canBlockReload||i.canSkipUntil)&&(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g));u&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(e,t)),a)}getDeliveryDirectives(e,t,s,i){let r=yr(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=pr),new Er(s,i,r)}checkRetry(e){const t=e.details,s=Cr(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Hr||!i.resolved&&r===Ur);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Or(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,i.resolved=!0}return o}}var Bn="NOT_LOADED",Un="APPENDING",Gn="PARTIAL",Hn="OK";class Vn{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Us.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Us.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Us.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Us.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let t=s.length;t--;){const i=s[t];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some((e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(a.body),s})):this.removeFragment(a.body))}))}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const s=e.frag,i=qn(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach((i=>{const a=s.elementaryStreams[i];if(!a)return;const o=t[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,e.part,l,o)})),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),Wn(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0;(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=jn(s,(t=>t.fragment.sn>=e)))}fragBuffered(e,t){const s=qn(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<i.length;e++){const t=i.start(e)-this.bufferPadding,s=i.end(e)+this.bufferPadding;if(l>=t&&o<=s){r.time.push({startPTS:Math.max(n,i.start(e)),endPTS:Math.min(a,i.end(e))});break}if(n<s&&a>t){const t=Math.max(n,i.start(e)),s=Math.min(a,i.end(e));s>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:s}))}else if(a<=t)break}return r}getPartialFragment(e){let t,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&Wn(h)&&(s=h.body.start-a,i=h.body.end+a,e>=s&&e<=i&&(t=Math.min(e-s,i-e),n<=t&&(r=h.body,n=t)))})),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Wn(t))}getState(e){const t=qn(e),s=this.fragments[t];return s?s.buffered?Wn(s)?Gn:Hn:Un:Bn}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=qn(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if("initSegment"===s.sn)return;const a=s.type;if(i){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=qn(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(e){const t=qn(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=jn(s,(e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((e=>e.clearElementaryStreamInfo()))}}function Wn(e){var t,s,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(s=e.range.audio)&&s.partial||null!=(i=e.range.audiovideo)&&i.partial)}function qn(e){return`${e.type}_${e.level}_${e.sn}`}function jn(e,t){return e.filter((e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s}))}class zn{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case sn:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case rn:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Kn{constructor(){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.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let e=0;e<4;e++)s[e]=t.getUint32(4*e);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)u[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],p=u[o],m=u[p];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[m^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],p=u[2],m=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r==0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r==4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^p[d[y>>>8&255]]^m[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],p=c[3];const m=new Int32Array(e),v=new Int32Array(m.length);let y,E,S,T,_,L,b,R,A,P,w,I,D,C;const k=this.networkToHostOrderSwap;for(;t<m.length;){for(A=k(m[t]),P=k(m[t+1]),w=k(m[t+2]),I=k(m[t+3]),_=A^r[0],L=I^r[1],b=w^r[2],R=P^r[3],D=4,C=1;C<i;C++)y=o[_>>>24]^l[L>>16&255]^h[b>>8&255]^d[255&R]^r[D],E=o[L>>>24]^l[b>>16&255]^h[R>>8&255]^d[255&_]^r[D+1],S=o[b>>>24]^l[R>>16&255]^h[_>>8&255]^d[255&L]^r[D+2],T=o[R>>>24]^l[_>>16&255]^h[L>>8&255]^d[255&b]^r[D+3],_=y,L=E,b=S,R=T,D+=4;y=n[_>>>24]<<24^n[L>>16&255]<<16^n[b>>8&255]<<8^n[255&R]^r[D],E=n[L>>>24]<<24^n[b>>16&255]<<16^n[R>>8&255]<<8^n[255&_]^r[D+1],S=n[b>>>24]<<24^n[R>>16&255]<<16^n[_>>8&255]<<8^n[255&L]^r[D+2],T=n[R>>>24]<<24^n[_>>16&255]<<16^n[L>>8&255]<<8^n[255&b]^r[D+3],v[t]=k(y^u),v[t+1]=k(T^f),v[t+2]=k(S^g),v[t+3]=k(E^p),u=A,f=P,g=w,p=I,t+=4}return v.buffer}}class Yn{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=function(e){switch(e){case sn:return"AES-CBC";case rn:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class Xn{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise(((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==sn||16!==t.byteLength)return ai.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=qi(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Kn),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Yn(this.subtle,t,i)}return this.fastAesKey.expandKey().then((t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new zn(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,t)})).catch((r=>(ai.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i))))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ai.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Qn=Math.pow(2,17);class Jn{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new ta({type:$s.NETWORK_ERROR,details:Bs.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(ea(e));e.gap=!1}const l=this.loader=r?new r(i):new n(i),h=Zn(e);e.loader=l;const d=Fr(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Qn};e.stats=l.stats;const u={onSuccess:(t,s,i,r)=>{this.resetLoader(e,l);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,i,r,n)=>{this.resetLoader(e,l),o(new ta({type:$s.NETWORK_ERROR,details:Bs.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Zs({url:s,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,s,i)=>{this.resetLoader(e,l),o(new ta({type:$s.NETWORK_ERROR,details:Bs.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,s,i)=>{this.resetLoader(e,l),o(new ta({type:$s.NETWORK_ERROR,details:Bs.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:t}))}};t&&(u.onProgress=(s,i,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(h,c,u)}))}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(ea(e,t));const l=this.loader=r?new r(i):new n(i),h=Zn(e,t);e.loader=l;const d=Fr(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Qn};t.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(e,l),o(new ta({type:$s.NETWORK_ERROR,details:Bs.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Zs({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new ta({type:$s.NETWORK_ERROR,details:Bs.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(e,l),o(new ta({type:$s.NETWORK_ERROR,details:Bs.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})}))}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Zn(e,t=null){const s=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(Os(r)&&Os(n)){var a;let t=r,s=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(s=n+(16-e%16)),0!==r&&(i.resetIV=!0,t=r-16)}i.rangeStart=t,i.rangeEnd=s}var o;return i}function ea(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:$s.MEDIA_ERROR,details:Bs.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new ta(i)}class ta extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class sa extends ei{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ia{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}const ra={length:0,start:()=>0,end:()=>0};class na{static isBuffered(e,t){if(e){const s=na.getBuffered(e);for(let e=s.length;e--;)if(t>=s.start(e)&&t<=s.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=na.getBuffered(e);return na.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=na.bufferedRanges(e);if(i.length)return na.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort(((e,t)=>e.start-t.start||t.end-e.end));let i=-1,r=[];if(s)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(i=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<s?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const h=r[e].start,d=r[e].end;if(-1===i&&t>=h&&t<=d&&(i=e),t+s>=h&&t<d)o=h,l=d,a=l-t;else if(t+s<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||ra}catch(e){return ai.log("failed to get media.buffered",e),ra}}}function aa(e,t){for(let i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function oa(e,t){const s=e.start+t;e.startPTS=s,e.setStart(s),e.endPTS=s+e.duration}function la(e,t){const s=t.fragments;for(let t=0,i=s.length;t<i;t++)oa(s[t],e);t.fragmentHint&&oa(t.fragmentHint,e),t.alignedSliding=!0}function ha(e,t){e&&(!function(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const s=Math.min(t.endCC,e.endCC),i=aa(t.fragments,s),r=aa(e.fragments,s);if(!i||!r)return;ai.log(`Aligning playlist at start of dicontinuity sequence ${s}`);la(i.start-r.start,e)}(t,e),t.alignedSliding||function(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const s=e.fragments,i=t.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=aa(i,a),n=aa(s,a));r&&n||(r=i[Math.floor(i.length/2)],n=aa(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;la((l-o)/1e3-(n.start-r.start),e)}(t,e),t.alignedSliding||t.skippedSegments||Dn(e,t,!1))}function da(e,t,s){ca(e,t,s),e.addEventListener(t,s)}function ca(e,t,s){e.removeEventListener(t,s)}const ua=function(e){let t="";const s=e.length;for(let i=0;i<s;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t},fa={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"};class ga extends sa{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=fa.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=na.bufferInfo(i||s,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${Os(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===fa.ENDED)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,i=t.start-s,r=t.start+t.duration+s;if(o||r<a.start||i>a.end){const e=n>r;(n<i||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===fa.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Jn(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Xn(e.config)}registerListeners(){const{hls:e}=this;e.on(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Us.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Us.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===fa.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=fa.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=na.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return na.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;da(s,"seeking",this.onMediaSeeking),da(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===fa.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ca(i,"seeking",this.onMediaSeeking),ca(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=fa.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,(e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===fa.FRAG_LOADING||!this.fragCurrent&&t===fa.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=fa.IDLE):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(Us.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((t=>{this.state!==fa.STOPPED&&this.state!==fa.ERROR&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Un){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Gn&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(Us.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:t}=this,{frag:s,payload:i}=e,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&nn(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,an(r.method)).catch((e=>{throw t.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),e})).then((i=>{const r=self.performance.now();return t.trigger(Us.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((t=>{this.state!==fa.STOPPED&&this.state!==fa.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==fa.STOPPED&&(this.state=fa.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,s=new Error("EME not supported (light build)");return this.warn(s.message),!e||e.mediaKeys?!1:(this.hls.trigger(Us.ERROR,{type:$s.KEY_SYSTEM_ERROR,details:Bs.KEY_SYSTEM_NO_KEYS,fatal:!0,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?ua(na.getBuffered(s)):"(detached)"})`),bi(e)){var i;if(e.type!==zs){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=fa.IDLE)}const t=null==(i=this.levels)?void 0:i[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=fa.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||0===r.length||r.some((e=>!e)),a=new ia(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=fa.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Us.KEY_LOADED,e),this.state===fa.KEY_LOADING&&(this.state=fa.IDLE),e})),this.hls.trigger(Us.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(bi(e)&&(!o||e.sn!==o.sn)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts&&bi(e)){const r=n.partList;if(r&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,s);if(o>-1){const l=r[o];let h;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=fa.FRAG_LOADING,h=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(e,l,t,i))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,i).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Us.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}var l;if(bi(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter((e=>e.loaded)).map((e=>`[${e.start}-${e.end}]`))}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),Os(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=fa.FRAG_LOADING;const h=this.config.progressive&&e.type!==zs;let d;return d=h&&a?a.then((t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,i))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,h?i:void 0),a]).then((([e])=>(!h&&i&&i(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Us.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,s,i){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,i).then((i=>{o[t.index]=i;const n=i.part;this.hls.trigger(Us.FRAG_LOADED,i);const a=Mn(s.details,e.sn,t.index+1)||xn(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===Bs.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===$s.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(Us.ERROR,t)}else this.hls.trigger(Us.ERROR,{type:$s.OTHER_ERROR,details:Bs.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==fa.PARSING)return void(this.fragCurrent||this.state===fa.STOPPED||this.state===fa.ERROR||(this.state=fa.IDLE));const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===zs)return!1;if(t>=r.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Mn(o,r,n):null,h=l?l.fragment:kn(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==fa.PARSING)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=qi(n,a)),!o.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:o};if(this.hls.trigger(Us.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!na.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,i=na.bufferInfo(t,s,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!Os(i))return null;const r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,r)}getFwdBufferInfoAtPos(e,t,s,i){const r=na.bufferInfo(e,t,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-t,i);return na.bufferInfo(e,t,s)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-3*t,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=qs){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const s=this.hls.startPosition,i=this.hls.liveSyncPosition,r=o?(-1!==s&&s>=n?s:i)||o.start:e;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}let h=this.filterReplacedPrimary(o,t);if(!h&&o){const e=o.sn-t.startSN;h=this.filterReplacedPrimary(s[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Hn||s===Gn&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==e&&s.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){return this.config,!1}filterReplacedPrimary(e,t){return e?(this.config,e):e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${o.start}`),i=a),r=l}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!Os(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const r=e[i];if(Dr(t,s,r))return r}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:r}=e;let n;return r&&(i=i.concat(r)),Pr(i,(e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=s?1:e.start>s?-1:0))),n||null}return null}(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=wr(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===Hn||t===Gn&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn||!s.live)){if(c.level===r.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Hn?t:null}}}return c}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&Os(r);if(n||!a&&!r){ha(s,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&Os(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&bi(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===fa.FRAG_LOADING_WAITING_RETRY)||(this.state=fa.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=t.details===Bs.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction;if(!a)return void(this.state=fa.ERROR);const{action:o,flags:l,retryCount:h=0,retryConfig:d}=a,c=!!d,u=c&&o===Hr,f=c&&!a.resolved&&l===Wr,g=null==(s=this.hls.latestLevelDetails)?void 0:s.live;if(!u&&f&&bi(i)&&!i.endList&&g&&!Mr(t))this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((u||f)&&h<d.maxNumRetry){var p;const s=$r(null==(p=t.response)?void 0:p.code),r=Or(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=fa.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${r}ms`)}else if(d){if(this.resetFragmentErrors(e),!(h<d.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${h})`);n||o===Gr||(a.resolved=!0)}else this.state=o===Ur?fa.WAITING_LEVEL:fa.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!$r(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=fa.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===fa.PARSING||this.state===fa.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===js&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==fa.STOPPED&&(this.state=fa.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=na.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===fa.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==fa.STOPPED&&(this.state=fa.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce(((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=i?0:Pn(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(Us.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)){var n;const t=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===s.fragmentError||t&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),t){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=fa.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(Us.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===qs?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(null!=(i=t&&!s?e.startPTS:(s||e).start)?i:NaN).toFixed(3)}-${(null!=(r=t&&!s?e.endPTS:(s||e).end)?r:NaN).toFixed(3)}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class pa{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];i.push(e),1!==i.length||s||this.executeNext(t)}appendBlocker(e){return new Promise((t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)}))}prependBlocker(e){return new Promise((t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(e[0].execute(),e.splice(0,1))}))}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(t){var s;if(i.onError(t),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[e])?void 0:s.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map((e=>e.label)).join(", "))||""}}const ma=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,va="HlsJsTrackRemovedError";class ya extends Error{constructor(e){super(e),this.name=va}}function Ea(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function Sa(e){return"audio"===e?1:0}class Ta{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Us.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Us.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Us.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Us.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Us.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Us.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Os(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter(((t,s)=>this.isLevelAllowed(t)&&s<=e));return this.clientRect=null,Ta.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;let i=e.length-1;const r=Math.max(t,s);for(let t=0;t<e.length;t+=1){const s=e[t];if((s.width>=r||s.height>=r)&&(n=s,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){i=t;break}}var n,a;return i}}function _a(e,t,s,i){e&&Object.keys(t).forEach((r=>{const n=e.filter((e=>e.groupId===r)).map((e=>{const n=Qs({},e);return n.details=void 0,n.attrs=new Xr(n.attrs),n.url=n.attrs.URI=La(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=i,n}));e.push(...n)}))}function La(e,t,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}var ba,Ra={exports:{}};var Aa=(ba||(ba=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function i(){}function r(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||e,a),l=s?s+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 a(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=s?s+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,r,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){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,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,n),!0;case 6:return d.fn.call(d.context,t,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),c){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,i);break;case 4:d[h].fn.call(d[h].context,t,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,i,r){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==t||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(Ra)),Ra.exports),Pa=oi(Aa);class wa{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:function(e,t){const s=new Uint8Array(t);let i=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Ia(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}function Da(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}function Ca(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function ka(e,t){const s=t;let i=0;for(;Da(e,t);){i+=10;i+=Ca(e,t+6),Ia(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(s,s+i)}function Ma(e,t){return 255===e[t]&&240==(246&e[t+1])}function xa(e,t){return 1&e[t+1]?7:9}function Oa(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Fa(e,t){return t+1<e.length&&Ma(e,t)}function Na(e,t){if(Fa(e,t)){const s=xa(e,t);if(t+s>=e.length)return!1;const i=Oa(e,t);if(i<=s)return!1;const r=t+i;return r===e.length||Fa(e,r)}return!1}function $a(e,t,s,i,r){if(!e.samplerate){const n=function(e,t,s,i){const r=t[s+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(Us.ERROR,Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[s+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d=n;5!==a&&29!==a||(d-=3);const c=[a<<3|(14&d)>>1,(1&d)<<7|o<<3];return ai.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(t,s,i,r);if(!n)return;Qs(e,n)}}function Ba(e){return 9216e4/e}function Ua(e,t,s,i,r){const n=i+r*Ba(e.samplerate),a=function(e,t){const s=xa(e,t);if(t+s<=e.length){const i=Oa(e,t)-s;if(i>0)return{headerLength:s,frameLength:i}}}(t,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-t.length);h?(o=new Uint8Array(l-r),o.set(t.subarray(s+r,t.length),0)):o=t.subarray(s+r,s+l);const d={unit:o,pts:n};return h||e.samples.push(d),{sample:d,length:l,missing:h}}const l=t.length-s;o=new Uint8Array(l),o.set(t.subarray(s,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Ga(e,t){return Da(e,t)&&Ca(e,t+6)+10<=e.length-t}function Ha(e,t=0,s=1/0){return function(e,t,s,i){const r=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=(c=e,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/n,l=(a+t)/n,h=Math.floor(Math.max(0,Math.min(l,o))),d=Math.floor(Math.min(h+Math.max(s,0),o));var c;return new i(r,h,d-h)}(e,t,s,Uint8Array)}function Va(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const i=fi(Ha(e.data,1,s)),r=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=fi(Ha(e.data,3+s,n));let o;return o="--\x3e"===i?fi(Ha(e.data,4+s+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+s+n)),t.mimeType=i,t.pictureType=r,t.description=a,t.data=o,t}function Wa(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=fi(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=fi(e.data.subarray(t),!0);t+=s.length+1;const i=fi(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=fi(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Va(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const s=fi(e.data.subarray(t),!0);t+=s.length+1;const i=fi(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=fi(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function qa(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=Ca(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}const ja=10,za=10;function Ka(e){let t=0;const s=[];for(;Da(e,t);){const i=Ca(e,t+6);e[t+5]>>6&1&&(t+=ja),t+=ja;const r=t+i;for(;t+za<r;){const i=qa(e.subarray(t)),r=Wa(i);r&&s.push(r),t+=i.size+ja}Ia(e,t)&&(t+=ja)}return s}function Ya(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Xa(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function Qa(e){const t=Ka(e);for(let e=0;e<t.length;e++){const s=t[e];if(Ya(s))return Xa(s)}}let Ja=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Za(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class eo{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=qi(this.cachedData,e),this.cachedData=null);let s,i=ka(e,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?Qa(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Os(o))&&(this.basePTS=to(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ja.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,s=r):r=l}else Ga(e,r)?(i=ka(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Ja.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const t=e.slice(s);this.cachedData?this.cachedData=qi(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:Za(),id3Track:a,textTrack:Za()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Za(),id3Track:this._id3Track,textTrack:Za()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const to=(e,t,s)=>{if(Os(e))return 90*e;return 9e4*t+(s?9e4*s.baseTime/s.timescale:0)};let so=null;const io=[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],ro=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],no=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ao=[0,1,1,4];function oo(e,t,s,i,r){if(s+24>t.length)return;const n=lo(t,s);if(n&&s+n.frameLength<=t.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function lo(e,t){const s=e[t+1]>>3&3,i=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*io[14*(3===s?3-i:3===i?3:4)+r-1],h=ro[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=no[s][i],u=ao[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===so){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);so=e?parseInt(e[1]):0}return!!so&&so<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function ho(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function co(e,t){return t+1<e.length&&ho(e,t)}function uo(e,t){if(t+1<e.length&&ho(e,t)){const s=4,i=lo(e,t);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=t+r;return n===e.length||co(e,n)}return!1}const fo=/\/emsg[-/]ID3/i;function go(e,t){return Os(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class po{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Xn(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,sn)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)s.set(e.subarray(t,t+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)e.set(s.subarray(i,i+16),t);return e}decryptAvcSample(e,t,s,i,r){const n=Xi(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)})).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void i();const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,i,n),this.decrypter.isSync())))return}}}}class mo{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,i=s.length;if(!i)return void t.dropped++;{const t=s[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,h,d=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(t,0),r=0,d=1);d<i;)if(o=t[d++],r)if(1!==r)if(o)if(1===o){if(l=d-r-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const s=this.getLastNalUnit(e.samples);s&&(n&&d<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=qi(s.data,t.subarray(0,l)),s.state=0))}d<i?(h=this.getNALuType(t,d),c=d,u=h,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const e={data:t.subarray(c,i),type:u,state:r};a.push(e)}if(0===a.length){const s=this.getLastNalUnit(e.samples);s&&(s.data=qi(s.data,t))}return e.naluState=r,a}}class vo{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&ai.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class yo extends mo{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach((i=>{var r,l;switch(i.type){case 1:{let t=!1;n=!0;const r=i.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Yi(i.data,1,s.pts,t.samples);break;case 7:{var d,c;n=!0,o=!0;const t=i.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(d=e.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const i=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}})),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new vo(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,i=8,r=8;for(let n=0;n<e;n++)0!==r&&(s=t.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(e){const t=new vo(e);let s,i,r,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),d=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),m=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=c();if(3===e&&f(1),p(),p(),f(1),u())for(i=3!==e?8:12,r=0;r<i;r++)u()&&m(r<6?16:64,t)}p();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();p(),f(1);const E=c(),S=c(),T=d(1);0===T&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let _=[1,1];if(u()&&u()){switch(h()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-T)*(S+1)*16-(T?2:4)*(o+l),pixelRatio:_}}}const Eo=188;class So{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=So.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(e){const t=e.length;let s=Math.min(940,t-Eo)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<t;o+=Eo){if(71!==e[o]||t-o!==Eo&&71!==e[o+Eo]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-Eo)+1)),r||(r=0===To(e,o)),r&&a>1&&(0===n&&a>2||o+Eo>s))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Di[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=So.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=So.createTrack("audio",i),this._id3Track=So.createTrack("id3"),this._txtTrack=So.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=qi(this.remainderData,e)).length,this.remainderData=null),y<Eo&&!i)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,So.syncOffset(e));y-=(y-E)%Eo,y<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let S=0;for(let t=E;t<y;t+=Eo)if(71===e[t]){const i=!!(64&e[t+1]),y=To(e,t);let S;if((48&e[t+3])>>4>1){if(S=t+5+e[t+4],S===t+Eo)continue}else S=t+4;switch(y){case h:i&&(d&&(r=Ao(d,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(S,t+Eo)),d.size+=t+Eo-S);break;case c:if(i){if(f&&(r=Ao(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(S,t+Eo)),f.size+=t+Eo-S);break;case u:i&&(g&&(r=Ao(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(S,t+Eo)),g.size+=t+Eo-S);break;case 0:i&&(S+=e[S]+1),v=this._pmtId=_o(e,S);break;case v:{i&&(S+=e[S]+1);const r=Lo(e,S,this.typeSupported,s,this.observer,this.logger);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===p||m||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${p}'. Backtracking to sync byte @${E} to parse all TS packets.`),p=null,t=E-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=y}}else S++;S>0&&bo(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const T={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(T),T}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,a=t.pesData,o=i.pesData;let l;if(n&&(l=Ao(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,a&&(l=Ao(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Ao(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new po(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){null===this.videoParser&&"avc"===e&&(this.videoParser=new yo)}decrypt(e,t){return new Promise((s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,(()=>{s(e)})):s(e)})):r.samples&&t.decryptAvcSamples(r.samples,0,0,(()=>{s(e)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r,n,a,o=t.data;if(i){this.aacOverFlow=null;const t=i.missing,r=i.sample.unit.byteLength;if(-1===t)o=qi(i.sample.unit,o);else{const n=r-t;i.sample.unit.set(o.subarray(0,t),n),e.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!Fa(o,r);r++);if(r!==s){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",bo(this.observer,new Error(e),t,this.logger),!t)return}if($a(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Ba(e.samplerate);a=i.sample.pts+t}}let l,h=0;for(;r<n;){if(l=Ua(e,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<n-1&&!Fa(o,r);r++);}}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(co(s,n)){const t=oo(e,s,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=Qs({},t,{type:this._videoTrack?Ja.emsg:Ja.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function To(e,t){return((31&e[t+1])<<8)+e[t+2]}function _o(e,t){return(31&e[t+10])<<8|e[t+11]}function Lo(e,t,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=To(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Ro("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!i){Ro("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Ro("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(-1===a.audioPid&&l>0){let s=t+5,i=l;for(;i>2;){if(106===e[s])n.warn("AC-3 in M2TS support not included in build");const t=e[s+1]+2;s+=t,i-=t}}break;case 194:case 135:return bo(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:return bo(r,new Error("Unsupported HEVC in M2TS found"),void 0,n),a}t+=l+5}return a}function bo(e,t,s,i){i.warn(`parsing error: ${t.message}`),e.emit(Us.ERROR,Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:t,reason:t.message})}function Ro(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Ao(e,t){let s,i,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=qi(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>e.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let d=r+9;if(e.size<=d)return null;e.size-=d;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(d){if(d>t){d-=t;continue}s=s.subarray(d),t-=d,d=0}c.set(s,o),o+=t}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}class Po{static getSilentFrame(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])}}}const wo=Math.pow(2,32)-1;class Io{static init(){let e;for(e in Io.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Io.types)Io.types.hasOwnProperty(e)&&(Io.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=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]),s=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]);Io.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Io.STTS=Io.STSC=Io.STCO=r,Io.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Io.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Io.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Io.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Io.FTYP=Io.box(Io.types.ftyp,n,o,n,a),Io.DINF=Io.box(Io.types.dinf,Io.box(Io.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return Io.box(Io.types.hdlr,Io.HDLR_TYPES[e])}static mdat(e){return Io.box(Io.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(wo+1)),i=Math.floor(t%(wo+1));return Io.box(Io.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(e){return Io.box(Io.types.mdia,Io.mdhd(e.timescale||0,e.duration||0),Io.hdlr(e.type),Io.minf(e))}static mfhd(e){return Io.box(Io.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Io.box(Io.types.minf,Io.box(Io.types.smhd,Io.SMHD),Io.DINF,Io.stbl(e)):Io.box(Io.types.minf,Io.box(Io.types.vmhd,Io.VMHD),Io.DINF,Io.stbl(e))}static moof(e,t,s){return Io.box(Io.types.moof,Io.mfhd(e),Io.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=Io.trak(e[t]);return Io.box.apply(null,[Io.types.moov,Io.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(Io.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=Io.trex(e[t]);return Io.box.apply(null,[Io.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(wo+1)),i=Math.floor(t%(wo+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Io.box(Io.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Io.box(Io.types.sdtp,s)}static stbl(e){return Io.box(Io.types.stbl,Io.stsd(e),Io.box(Io.types.stts,Io.STTS),Io.box(Io.types.stsc,Io.STSC),Io.box(Io.types.stsz,Io.STSZ),Io.box(Io.types.stco,Io.STCO))}static avc1(e){let t,s,i,r=[],n=[];for(t=0;t<e.sps.length;t++)s=e.sps[t],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(t=0;t<e.pps.length;t++)s=e.pps[t],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=Io.box(Io.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return Io.box(Io.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,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Io.box(Io.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Io.box(Io.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return Io.box(Io.types.mp4a,Io.audioStsd(e),Io.box(Io.types.esds,Io.esds(e)))}static mp3(e){return Io.box(Io.types[".mp3"],Io.audioStsd(e))}static ac3(e){return Io.box(Io.types["ac-3"],Io.audioStsd(e),Io.box(Io.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return Io.box(Io.types.stsd,Io.STSD,Io.mp4a(e));if("mp3"===t&&"mp3"===e.codec)return Io.box(Io.types.stsd,Io.STSD,Io.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return Io.box(Io.types.stsd,Io.STSD,Io.avc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(wo+1)),a=Math.floor(s%(wo+1));return Io.box(Io.types.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const s=Io.sdtp(e),i=e.id,r=Math.floor(t/(wo+1)),n=Math.floor(t%(wo+1));return Io.box(Io.types.traf,Io.box(Io.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),Io.box(Io.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Io.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,Io.box(Io.types.trak,Io.tkhd(e),Io.mdia(e))}static trex(e){const t=e.id;return Io.box(Io.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<i;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Io.box(Io.types.trun,n)}static initSegment(e){Io.types||Io.init();const t=Io.moov(e);return qi(Io.FTYP,t)}static hvc1(e){return new Uint8Array}}Io.types=void 0,Io.HDLR_TYPES=void 0,Io.STTS=void 0,Io.STSC=void 0,Io.STCO=void 0,Io.STSZ=void 0,Io.VMHD=void 0,Io.SMHD=void 0,Io.STSD=void 0,Io.FTYP=void 0,Io.DINF=void 0;function Do(e,t=!1){return function(e,t,s=1,i=!1){const r=e*t*s;return i?Math.round(r):r}(e,1e3,1/9e4,t)}function Co(e){const{baseTime:t,timescale:s,trackId:i}=e;return`${t/s} (${t}/${s}) trackId: ${i}`}let ko,Mo=null,xo=null;function Oo(e,t,s,i){return{duration:t,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Fo extends ei{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,null===Mo){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Mo=e?parseInt(e[1]):0}if(null===xo){const e=navigator.userAgent.match(/Safari\/(\d+)/i);xo=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?Co(t):t} > ${e?Co(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce(((e,i)=>{let r=i.pts,n=r-e;return n<-4294967296&&(t=!0,r=No(r,s),n=r-e),n>0?e:r}),s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,p=r;const m=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!m||E)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var T,_,L,b;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(_=e.pixelRatio)?void 0:_[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(b=e.pixelRatio)?void 0:b[1]))||!e&&S||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,n));const s=this.isVideoContiguous;let i,a=-1;if(S&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,p+=(t.samples[0].pts-e)/t.inputTimeScale,i=p}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&S){const s=this.getVideoStartPts(t.samples),i=(No(e.samples[0].pts,s)-s)/t.inputTimeScale;g+=Math.max(0,i),p+=Math.max(0,-i)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||S||o===js?p:void 0),S){const i=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,s,i)}}else S&&(l=this.remuxVideo(t,p,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=$o(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Bo(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=No(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4",g=-1;if(u&&(h=d=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Io.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,c=e.inputTimeScale,l&&c===l.timescale?u=!1:h=d=this.computeInitPts(r[0].pts,c,s,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Io.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=No(n[0].dts,e),i=this.computeInitPts(t,c,s,"video"),r=this.computeInitPts(e,c,s,"video");d=Math.min(d,i),h=Math.min(h,r)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${h/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/c} (${h}/${c}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:c,trackId:g},this._initDTS={baseTime:d,timescale:c,trackId:g}):h=c=void 0,{tracks:o,initPTS:h,timescale:c,trackId:g}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let d,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!s||null===u){const e=h+t*r,i=n[0].pts-No(n[0].dts,n[0].pts);Mo&&null!==u&&Math.abs(e-i-(u+h))<15e3?s=!0:u=e-i-h}const y=u+h;for(let e=0;e<o;e++){const t=n[e];t.pts=No(t.pts,y),t.dts=No(t.dts,y),t.dts<n[e>0?e-1:e].dts&&(v=!0)}v&&n.sort((function(e,t){const s=e.dts-t.dts,i=e.pts-t.pts;return s||i})),d=n[0].dts,c=n[n.length-1].dts;const E=c-d,S=E?Math.round(E/(o-1)):g||e.inputTimeScale/30;if(s){const s=d-y,i=s>S,r=s<-1;if((i||r)&&(i?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Do(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Do(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||y>=n[0].pts||Mo)){d=y;const e=n[0].pts-s;if(i)n[0].dts=d,n[0].pts=e;else{let t=!0;for(let i=0;i<n.length&&!(n[i].dts>e&&t);i++){const e=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i<n.length-1){const s=n[i+1].pts;t=s<=n[i].pts==s<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${Do(e,!0)}/${Do(d,!0)}, delta: ${Do(s,!0)} ms`)}}d=Math.max(0,d);let T=0,_=0,L=d;for(let e=0;e<o;e++){const t=n[e],s=t.units,i=s.length;let r=0;for(let e=0;e<i;e++)r+=s[e].data.length;_+=r,T+=i,t.length=r,t.dts<L?(t.dts=L,L+=S/4|0||1):L=t.dts,p=Math.min(t.pts,p),m=Math.max(t.pts,m)}c=n[o-1].dts;const b=_+4*T+8;let R;try{R=new Uint8Array(b)}catch(e){return void this.observer.emit(Us.ERROR,Us.ERROR,{type:$s.MUX_ERROR,details:Bs.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:b,reason:`fail allocating video mdat ${b}`})}const A=new DataView(R.buffer);A.setUint32(0,b),R.set(Io.types.mdat,4);let P=!1,w=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,D=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],s=t.units;let l,d=0;for(let e=0,t=s.length;e<t;e++){const t=s[e],i=t.data,r=t.data.byteLength;A.setUint32(f,r),f+=4,R.set(i,f),f+=r,d+=4+r}if(e<o-1)g=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const s=this.config,a=e>0?t.dts-n[e-1].dts:S;if(l=e>0?t.pts-n[e-1].pts:S,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(s.maxBufferHole*r),n=(i?p+i*r:this.nextAudioTs+h)-t.pts;n>e?(g=n-a,g<0?g=a:P=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const c=Math.round(t.pts-t.dts);w=Math.min(w,g),D=Math.max(D,g),I=Math.min(I,l),C=Math.max(C,l),a.push(Oo(t.key,g,d,c))}if(a.length)if(Mo){if(Mo<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(xo&&C-I<D-w&&S/D<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=d;for(let t=0,s=a.length;t<s;t++){const i=e+a[t].duration,r=e+a[t].cts;if(t<s-1){const e=i+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:S;a[t].cts=0,e=i}}g=P||!g?S:g;const k=c+g;this.nextVideoTs=u=k-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const M={data1:Io.moof(e.sequenceNumber++,d,Qs(e,{samples:a})),data2:R,startPTS:(p-h)/r,endPTS:(m+g-h)/r,startDTS:(d-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,M}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=e.samples,g=d?0:8,p=this.nextAudioTs||-1;const m=h.baseTime*n/h.timescale,v=m+t*n;if(this.isAudioContiguous=s=s||f.length&&p>0&&(i&&Math.abs(v-(p+m))<9e3||Math.abs(No(f[0].pts,v)-(p+m))<20*l),f.forEach((function(e){e.pts=No(e.pts,v)})),!s||p<0){const e=f.length;if(f=f.filter((e=>e.pts>=0)),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${m} / ${n})`),!f.length)return;p=0===r?0:i&&!u?Math.max(0,v-m):f[0].pts-m}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,i=p+m;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,h=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===s&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=p=a-m,i=a);else if(o>=t*l&&h<1e4&&u){let t=Math.round(o/l);for(i=a-t*l;i<0&&t&&l;)t--,i+=l;0===s&&(this.nextAudioTs=p=i-m),this.warn(`Injecting ${t} audio frames @ ${((i-m)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=Po.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),f.splice(s,0,{unit:t,pts:i}),i+=l,s++}}r.pts=i,i+=l}}let y,E=null,S=null,T=0,_=f.length;for(;_--;)T+=f[_].unit.byteLength;for(let t=0,i=f.length;t<i;t++){const i=f[t],r=i.unit;let n=i.pts;if(null!==S){c[t-1].duration=Math.round((n-S)/a)}else{if(s&&"aac"===e.segmentCodec&&(n=p+m),E=n,!(T>0))return;T+=g;try{y=new Uint8Array(T)}catch(e){return void this.observer.emit(Us.ERROR,Us.ERROR,{type:$s.MUX_ERROR,details:Bs.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:T,reason:`fail allocating audio mdat ${T}`})}if(!d){new DataView(y.buffer).setUint32(0,T),y.set(Io.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,c.push(Oo(!0,o,l,0)),S=n}const L=c.length;if(!L)return;const b=c[c.length-1];p=S-m,this.nextAudioTs=p+a*b.duration;const R=d?new Uint8Array(0):Io.moof(e.sequenceNumber++,E/a,Qs({},e,{samples:c}));e.samples=[];const A=(E-m)/n,P=this.nextAudioTs/n,w={data1:R,data2:y,startPTS:A,endPTS:P,startDTS:A,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,w}}function No(e,t){let s;if(null===t)return e;for(s=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=s;return e}function $o(e,t,s,i){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=No(r.pts-s.baseTime*n/s.timescale,t*n)/n,r.dts=No(r.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function Bo(e,t,s){const i=e.samples.length;if(!i)return;const r=e.inputTimeScale;for(let n=0;n<i;n++){const i=e.samples[n];i.pts=No(i.pts-s.baseTime*r/s.timescale,t*r)/r}e.samples.sort(((e,t)=>e.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}function Uo(e,t,s=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(s?e.duration:0))/e.timescale:t}function Go(e,t,s){const i=e.codec;if(i&&i.length>4)return i;if(t===Si){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return or(i,!1)}return s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{ko=self.performance.now.bind(self.performance)}catch(e){ko=Date.now}const Ho=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Za("video",1),n=this.audioTrack=Za("audio",1),a=this.txtTrack=Za("text",1);if(this.id3Track=Za("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=$i(e);if(o.video){const{id:e,timescale:t,codec:s,supplemental:i}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=s,r.supplemental=i}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=Di.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let s=0;s<t;){const i=Mi(e,s);if(i>8&&109===e[s+4]&&111===e[s+5]&&111===e[s+6]&&102===e[s+7])return!0;s=i>1?s+i:t}return!1}(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=qi(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},s=Fi(e,["moof"]);if(s.length<2)return t.remainder=e,t;const i=s[s.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(s);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=ji(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=ji(e,t),{videoTrack:t,audioTrack:Za(),id3Track:i,textTrack:Za()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Fi(e.samples,["emsg"]);i&&i.forEach((e=>{const i=function(e){const t=e[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==Ci(e.subarray(h,h+1));)s+=Ci(e.subarray(h,h+1)),h+=1;for(s+=Ci(e.subarray(h,h+1)),h+=1;"\0"!==Ci(e.subarray(h,h+1));)i+=Ci(e.subarray(h,h+1)),h+=1;i+=Ci(e.subarray(h,h+1)),h+=1,r=Mi(e,12),n=Mi(e,16),o=Mi(e,20),l=Mi(e,24),h=28}else if(1===t){h+=4,r=Mi(e,h),h+=4;const t=Mi(e,h);h+=4;const n=Mi(e,h);for(h+=4,a=2**32*t+n,Fs(a)||(a=Number.MAX_SAFE_INTEGER,ai.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Mi(e,h),h+=4,l=Mi(e,h),h+=4;"\0"!==Ci(e.subarray(h,h+1));)s+=Ci(e.subarray(h,h+1)),h+=1;for(s+=Ci(e.subarray(h,h+1)),h+=1;"\0"!==Ci(e.subarray(h,h+1));)i+=Ci(e.subarray(h,h+1)),h+=1;i+=Ci(e.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(fo.test(i.schemeIdUri)){const e=go(i,t);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:Ja.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=go(i,t);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:e,pts:e,type:Ja.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends ei{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=$i(e);if(t)!function(e,t){if(!e||!t)return;const s=t.keyId;s&&t.isCommonEncryption&&Wi(e,((e,t)=>{const i=e.subarray(8,24);i.some((e=>0!==e))||(ai.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${gi(i)} -> ${gi(s)}`),e.set(s,8))}))}(e,t);else{const e=r||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(s=Go(r,Si,this)),n&&(i=Go(n,Ti,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};Os(h)||(h=this.lastEndTime=r||0);const c=t.samples;if(!c.length)return d;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,s){const i={},r=Fi(e,["moof","traf"]);for(let e=0;e<r.length;e++){const n=r[e],a=Fi(n,["tfhd"])[0],o=Mi(a,4),l=t[o];if(!l)continue;i[o]||(i[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=i[o],d=Fi(n,["tfdt"])[0];if(d){const e=d[0];let t=Mi(d,4);1===e&&(t===wi?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=wi+1,t+=Mi(d,8))),Os(t)&&(!Os(h.start)||t<h.start)&&(h.start=t)}const c=l.default,u=Mi(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=Mi(a,2&u?12:8));const g=Fi(n,["trun"]);let p=h.start||0,m=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],s=Mi(t,4),i=h.sampleCount;h.sampleCount+=s;const r=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],d=8&t[2];let c=8,u=s;for(r&&(c+=4),n&&s&&(1&t[c+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=i),c+=4,a?(v=Mi(t,c),c+=4):v=f,o&&(c+=4),d&&(c+=4),p+=v,m+=v,u--);u--;)a?(v=Mi(t,c),c+=4):v=f,o&&(c+=4),l&&(1&t[c+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(u+1),h.keyFrameStart=p),c+=4),d&&(c+=4),p+=v,m+=v;!m&&f&&(m+=f*s)}h.duration+=m}if(!Object.keys(i).some((e=>i[e].duration))){let t=1/0,s=0;const r=Fi(e,["sidx"]);for(let e=0;e<r.length;e++){const i=Ni(r[e]);if(null!=i&&i.references){t=Math.min(t,i.earliestPresentationTime/i.timescale);const e=i.references.reduce(((e,t)=>e+t.info.duration||0),0);s=Math.max(s,e+i.earliestPresentationTime/i.timescale)}}s&&Os(s)&&Object.keys(i).forEach((e=>{i[e].duration||(i[e].duration=s*i[e].timescale-i[e].start)}))}return i}(c,f,this),p=f.audio?g[f.audio.id]:null,m=f.video?g[f.video.id]:null,v=Uo(m,1/0),y=Uo(p,1/0),E=Uo(m,0,!0),S=Uo(p,0,!0);let T=r,_=0;const L=p&&(!m||!l&&y<v||l&&l.trackId===f.audio.id),b=L?p:m;if(b){const e=b.timescale,t=b.start-r*e,s=L?f.audio.id:f.video.id;T=b.start/e,_=L?S-y:E-v,!n&&l||!function(e,t,s,i){if(null===e)return!0;const r=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>r}(l,T,r,_)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${T-r} (${t}/${e}) trackId: ${s}`),l=null,u.initPTS=t,u.timescale=e,u.trackId=s)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=T,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const R=T-l.baseTime/l.timescale,A=R+_;_>0?this.lastEndTime=A:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const P=!!f.audio,w=!!f.video;let I="";P&&(I+="audio"),w&&(I+="video");const D={data1:c,startPTS:R,startDTS:R,endPTS:A,endDTS:A,type:I,hasAudio:P,hasVideo:w,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};d.audio=P&&!w?D:void 0,d.video=w?D:void 0;const C=null==m?void 0:m.sampleCount;if(C){const e=m.keyFrameIndex,t=-1!==e;D.nb=C,D.dropped=0===e||this.isVideoContiguous?0:t?e:C,D.independent=t,D.firstKeyFrame=e,t&&m.keyFrameStart&&(D.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),D.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${C} dropped: ${D.dropped} start: ${D.firstKeyFramePTS||"NA"}`)}return d.initSegment=u,d.id3=$o(s,r,l,l),i.samples.length&&(d.text=Bo(i,r,l)),d}}},{demux:So,remux:Fo},{demux:class extends eo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=ka(e,0);let i=(null==s?void 0:s.length)||0;if(uo(e,i))return!1;for(let s=e.length;i<s;i++)if(Na(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Ma(e,t)&&Oa(e,t)<=e.length-t}(e,t)}appendFrame(e,t,s){$a(e,this.observer,t,s,e.manifestCodec);const i=Ua(e,t,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:Fo},{demux:class extends eo{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ka(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==Qa(t)&&((e,t)=>{let s=0,i=5;t+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],t+=1,i-=o}return s})(e,s)<=16)return!1;for(let t=e.length;s<t;s++)if(uo(e,s))return ai.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return ho(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return oo(e,t,s,this.basePTS,this.frameIndex)}},remux:Fo}];class Vo{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=ko();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=o,E=function(e,t){let s=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t);return s}(n,t);if(E&&nn(E.method)){const e=this.getDecrypter(),t=an(E.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,t).then((e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t})),this.decryptionPromise;{let i=e.softwareDecrypt(n,E.key.buffer,E.iv.buffer,t);if(s.part>-1){const t=e.flush();i=t?t.buffer:t}if(!i)return r.executeEnd=ko(),Wo(s);n=new Uint8Array(i)}}const S=this.needsProbing(h,d);if(S){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(Us.ERROR,Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=ko(),Wo(s)}(h||d||f||S)&&this.resetInitSegment(y,g,p,v,t),(h||f||S)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const T=this.transmux(n,E,u,c,s);this.asyncResult=qo(T);const _=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,r.executeEnd=ko(),T}flush(e){const t=e.transmuxing;t.executeStart=ko();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then((()=>this.flush(e)));const n=[],{timeOffset:a}=i;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=ko();const s=[Wo(e)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a);return qo(h)?(this.asyncResult=!0,h.then((t=>(this.flushRemux(n,t,e),n)))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===qs?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=ko()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,s,i),a.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,s,i,r):this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,i,!1,this.id),chunkMeta:r})))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let t=0,s=Ho.length;t<s;t++){var n;if(null!=(n=Ho[t].demux)&&n.probe(e,this.logger)){r=Ho[t];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,h=r.demux;o&&o instanceof l||(this.remuxer=new l(s,t,i,this.logger)),a&&a instanceof h||(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Xn(this.config)),e}}const Wo=e=>({remuxResult:{},chunkMeta:e});function qo(e){return"then"in e&&e.then instanceof Function}class jo{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class zo{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}const Ko=/(\d+)-(\d+)\/(\d+)/;class Yo{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Xo,this.controller=new self.AbortController,this.stats=new Ei}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Qs({},e.headers))};e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return s}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&Os(o)?o:l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))}),t.timeout);(qo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var r;this.response=this.loader=s;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))}),l-(a-i.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new Qo(t||"fetch, bad network response",e,s)}i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Ko.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Os(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(s.headers)||i.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&Os(t.highWaterMark)?this.loadProgressively(s,i,e,t.highWaterMark,o):n?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=s[a];l&&(i.loaded=i.total=l);const h={url:o.url,data:s,code:o.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!Os(t.highWaterMark)&&d(i,e,s,o),null==(n=this.callbacks)||n.onSuccess(h,i,e,o)})).catch((t=>{var s;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(s=this.callbacks)||s.onError({code:r,text:n},e,t?t.details:null,i)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new wa,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,l.buffer,e),o()})).catch((()=>Promise.reject()));return o()}}function Xo(e,t){return new self.Request(e.url,t)}class Qo extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Jo=/^age:\s*[\d.]+\s*$/im;class Zo{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ei,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,t.url)})).catch((e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r(s,t.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)})).catch((e=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:e.message},t,s,i)})):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[t]);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,self.clearTimeout(this.requestTimeout),s.timeout=r&&Os(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,l="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=null!=l?l:t.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,e,r,t);const h={url:t.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(h,s,e,t))}}const h=r.loadPolicy.errorRetry;var o;if(Nr(h,s.retry,!1,{url:e.url,data:void 0,code:i}))this.retry(h);else ai.error(`${i} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:i,text:t.statusText},e,t,s)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Nr(e,this.stats.retry,!0))this.retry(e);else{var t;ai.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Or(e,s.retry),s.retry++,ai.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Jo.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const el={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},tl=Zs(Zs({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Zo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends ei{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,h=i?i.duration:s.duration,d=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,p=!!e||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(d<=Math.max(v,h/(2*y)*1e3))return;const E=m?m.len/y:0,S=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&S>-1,_=this.getBwEstimate(),L=r.levels,b=L[u],R=Math.max(l.loaded,Math.round(h*(s.bitrate||b.averageBitrate)/8));let A=T?d-S:d;A<1&&T&&(A=Math.min(d,8*l.loaded/_));const P=T?1e3*l.loaded/A:0,w=v/1e3,I=P?(R-l.loaded)/P:8*R/_+w;if(I<=E)return;const D=P?8*P:_,C=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),k=this.hls.config.abrBandWidthUpFactor;let M,x=Number.POSITIVE_INFINITY;for(M=u-1;M>c;M--){const e=L[M].maxBitrate,t=!L[M].details||C;if(x=this.getTimeToLoadFrag(w,D,h*e,t),x<Math.min(E,h+w))break}if(x>=I)return;if(x>10*h)return;T?this.bwEstimator.sample(d-Math.min(v,S),l.loaded):this.bwEstimator.sampleTTFB(d);const O=L[M].maxBitrate;this.getBwEstimate()*k>O&&this.resetEstimator(O);const F=this.findBestLevel(O,c,M,0,E,1,1);F>-1&&(M=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${I.toFixed(3)} s\n Estimated load time for down switch fragment: ${x.toFixed(3)} s\n TTFB estimate: ${0|S} ms\n Current BW estimate: ${Os(_)?0|_:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|O} bps`),r.nextLoadLevel=r.nextAutoLevel=M,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===M&&M>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,M>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,M,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||I>2*x?N():this.timer=self.setInterval(N,1e3*x),r.trigger(Us.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Ys(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.FRAG_LOADING,this.onFragLoading,this),e.on(Us.FRAG_LOADED,this.onFragLoaded,this),e.on(Us.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Us.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Us.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Us.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Us.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.FRAG_LOADING,this.onFragLoading,this),e.off(Us.FRAG_LOADED,this.onFragLoaded,this),e.off(Us.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Us.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Us.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Us.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Us.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case Bs.BUFFER_ADD_CODEC_ERROR:case Bs.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Bs.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:i}=this;if(e&&s&&e.sn===s.sn&&e.level===s.level){const t=performance.now(),s=i?i.stats:e.stats,r=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;Os(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===qs&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=s?s.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(Us.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==qs||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===f.length)return 0;const v=f[d],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===p||-1===h;let S,T="SDR",_=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:b}=m;this.audioTracksByGroup||(this.audioTracksByGroup=Rr(g));let R=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(e,t,s,i){return e.slice(s,i+1).reduce(((e,t,s)=>{if(!t.codecSet)return e;const i=t.audioGroups;let r=e[t.codecSet];r||(e[t.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,t.bitrate);const n=Math.min(t.height,t.width);return r.minHeight=Math.min(r.minHeight,n),r.minFramerate=Math.min(r.minFramerate,t.frameRate),r.minIndex=Math.min(r.minIndex,s),r.maxScore=Math.max(r.maxScore,t.score),r.fragmentError+=t.fragmentError,r.videoRanges[t.videoRange]=(r.videoRanges[t.videoRange]||0)+1,e}),{})}(f,0,t,s)),r=function(e,t,s,i,r){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let d=!1,c=!1,u=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=_r(t,r);for(let t=n.length;t--;){const s=e[n[t]];d||(d=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate),E.filter((e=>s.videoRanges[e]>0)).length>0&&(c=!0)}u=Os(u)?u:0,f=Os(f)?f:0;const S=Math.max(1080,u),T=Math.max(30,f);g=Os(g)?g:s,s=Math.max(g,s),c||(t=void 0);const _=n.length>1;return{codecSet:n.reduce(((t,i)=>{const r=e[i];if(i===t)return t;if(v=c?E.filter((e=>r.videoRanges[e]>0)):[],_){if(r.minBitrate>s)return br(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),t;if(!r.hasDefaultAudio)return br(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return br(i,`audio codec preference "${o}" not found`),t;if(a&&!h){if(!r.channels[a])return br(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||h)&&d&&0===r.channels[2])return br(i,"no renditions with stereo sound found"),t;if(r.minHeight>S)return br(i,`min resolution of ${r.minHeight} > maximum of ${S}`),t;if(r.minFramerate>T)return br(i,`min framerate of ${r.minFramerate} > maximum of ${T}`),t;if(!v.some((e=>r.videoRanges[e]>0)))return br(i,`no variants with VIDEO-RANGE of ${Lr(v)} found`),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return br(i,`video codec preference "${l}" not found`),t;if(r.maxScore<m)return br(i,`max score of ${r.maxScore} < selected max of ${m}`),t}return t&&(rr(i)>=rr(t)||r.fragmentError>e[t].fragmentError)?t:(p=r.minIndex,m=r.maxScore,i)}),void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(i,T,e,L,b),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:d}=r;R=h,S=n,T=d?a[a.length-1]:a[0],_=o,e=Math.max(e,l),this.log(`picked start tier ${Lr(r)}`)}else S=null==v?void 0:v.codecSet,T=null==v?void 0:v.videoRange;const A=u?u.duration:c?c.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let o=s;o>=t;o--){var I;const t=f[o],c=o>d;if(!t)continue;if((S&&t.codecSet!==S||T&&t.videoRange!==T||c&&_>t.frameRate||!c&&_>0&&_<t.frameRate||null!=(I=t.supportedResult)&&null!=(I=I.decodingInfoResults)&&I.some((e=>!1===e.smooth)))&&(!E||o!==R)){w.push(o);continue}const g=t.details,m=(u?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||A;let v;v=c?a*e:n*e;const L=A&&i>=2*A&&0===r?t.averageBitrate:t.maxBitrate,b=this.getTimeToLoadFrag(P,v,L*m,void 0===g);if(v>=L&&(o===h||0===t.loadError&&0===t.fragmentError)&&(b<=P||!Os(b)||y&&!this.bitrateTestDelay||b<l)){const e=this.forcedAutoLevel;return o===p||-1!==e&&e===p||(w.length&&this.trace(`Skipped level(s) ${w.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[w[0]].codecs}" ${f[w[0]].videoRange}; not compatible with "${S}" ${T}`),this.info(`switch candidate:${d}->${o} adjustedbw(${Math.round(v)})-bitrate=${Math.round(v-L)} ttfb:${P.toFixed(1)} avgDuration:${m.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${b.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},bufferController:class extends ei{constructor(e,t){var s;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Us.MEDIA_ATTACHED,{media:t,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(s=ui(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Us.BUFFER_RESET,this.onBufferReset,this),e.on(Us.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Us.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Us.BUFFER_EOS,this.onBufferEos,this),e.on(Us.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Us.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Us.FRAG_PARSED,this.onFragParsed,this),e.on(Us.FRAG_CHANGED,this.onFragChanged,this),e.on(Us.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Us.BUFFER_RESET,this.onBufferReset,this),e.off(Us.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Us.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Us.BUFFER_EOS,this.onBufferEos,this),e.off(Us.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Us.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Us.FRAG_PARSED,this.onFragParsed,this),e.off(Us.FRAG_CHANGED,this.onFragChanged,this),e.off(Us.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?Qs(s,i.tracks):this.sourceBuffers.forEach((e=>{const[t]=e;t&&(s[t]=Qs({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null})),{media:e,mediaSource:t,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=ui(this.appendSource);if(i){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(r),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&r instanceof t,Ea(s),function(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then((()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()}))};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Lr(s,((e,t)=>"initSegment"===e?void 0:t))};\ntransfer tracks: ${Lr(i,((e,t)=>"initSegment"===e?void 0:t))}}`),!function(e,t){const s=Object.keys(e),i=Object.keys(t),r=s.length,n=i.length;return!r||!n||r===n&&!s.some((e=>-1===i.indexOf(e)))}(i,s)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(Us.MEDIA_DETACHING,{}),this.onMediaAttaching(Us.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach((e=>{const t=e,s=i[t];if(s){const e=s.buffer;if(e){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=na.getBuffered(e);i.detectEvictedFragments(t,s,r,null,!0)}const n=Sa(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach((([e])=>{e&&this.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),r.removeSourceBuffer(t[s]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Ea(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Us.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach((([e])=>{e&&this.resetBuffer(e)})),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Sa(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new pa(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some((e=>!i[e]));n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach((e=>{var s,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=i[e];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[e],g=null!=f&&f.buffer?f:u,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;u||(u=i[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=lr(p,m),y=null==v?void 0:v.replace(ma,"$1");let E=lr(o,l);const S=null==(r=E)?void 0:r.replace(ma,"$1");E&&v&&y!==S&&("audio"===e.slice(0,5)&&(E=or(E,this.appendSource)),this.log(`switching codec ${p} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=h,this.appendChangeType(e,h,E))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(s=t.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e}),{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,qs))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>i||null!=t&&t.buffer&&na.isBuffered(t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,qs))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:h}=t,d=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();d.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;0===g.start&&(g.start=f),p&&0===p.start&&(p.start=f);const m=s.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==m?void 0:m.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=s.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==c){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const s=e.end;if(t){const e=t.frag.start;(s>e||s<this.lastVideoAppendEnd||na.isBuffered(E,e))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const t=e.start+.05*e.duration,s=E.buffered,i=this.currentOp("video");s.length||i?!i&&!na.isBuffered(E,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const S=(o||a).start,T={label:`append-${r}`,execute:()=>{var e;d.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,S,.1,r,c,u):void 0!==h&&Os(h)&&this.updateTimestampOffset(t,h,1e-6,r,c,u)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);const t={};this.sourceBuffers.forEach((([e,s])=>{e&&(t[e]=na.getBuffered(s))})),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Us.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const s={type:$s.MEDIA_ERROR,parent:a.type,details:Bs.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},i=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)s.details=Bs.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)s.errorAction=zr(!0);else if(e.name===va&&0===this.sourceBufferCount)s.errorAction=zr(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${i||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||i)&&(s.fatal=!0)}this.hls.trigger(Us.ERROR,s)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===qs?"level":"track"} ${a.level} cc: ${u}`),this.append(T,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Us.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach((([e])=>{e&&this.append(this.getFlushOp(e,i,r),e)}))}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[_i]?r.push("audiovideo"):(n[Si]&&r.push("audio"),n[Ti]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const e=self.performance.now();s.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:s.stats;this.hls.trigger(Us.FRAG_BUFFERED,{frag:s,part:i,stats:t,id:s.type})}),r).catch((e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1}))}onBufferEos(e,t){var s;this.sourceBuffers.forEach((([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}}));const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)}))?i?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(Us.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(Us.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach((([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen((()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)}))}onError(e,t){if(t.details===Bs.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;Os(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||null===t)return;if(!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(Os(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}const o=i.frontBufferFlushThreshold;if(Os(o)&&o>0){const e=Math.max(i.maxBufferLength,o),t=Math.max(e,n),s=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach((([e,t])=>{if(t){const r=na.getBuffered(t);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger(Us.BACK_BUFFER_REACHED,{bufferEnd:s});const t=this.tracks[e];if(null!=(i=this.details)&&i.live)this.hls.trigger(Us.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Us.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:e})}}}))}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach((([t,i])=>{if(i){const r=na.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||e>=a&&e<=o)return;this.hls.trigger(Us.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}}))}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,i)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return Os(r)?{duration:r}:null;const n=this.media.duration;return i>(Os(s.duration)?s.duration:0)&&i>n||!Os(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==e&&(Os(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Lr(s)}`),this.tracksReady){var i;const e=null==(i=this.transferData)?void 0:i.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach((([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}})),this.hls.trigger(Us.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([e])=>{this.executeNext(e)}))}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${Lr(a)}`);try{const e=s.addSourceBuffer(r),i=Sa(n),o=[n,e];t[i]=o,a.buffer=e}catch(e){var i;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&("video"===t||"audiovideo"===t)&&er(s,"video")&&(i=function(e,t){const s=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)Zi(t[e],"video")||s.push(t[e])}return t&&s.push(t),s.join(",")}(i,s));const r=lr(i,e.levelCodec);return r?"audio"===t.slice(0,5)?or(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((e,t)=>{const s=t.removedRanges;null!=s&&s.length&&this.hls.trigger(Us.BUFFER_FLUSHED,{type:e})}))}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=Os(i.duration)?i.duration:1/0,l=Os(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(s,o,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),a.remove(h,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=null==s?void 0:s.buffer;if(!i)throw new ya(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some((([e,t])=>e&&t.updating))}isQueued(){return this.sourceBuffers.some((([e])=>e&&!!this.currentOp(e)))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map((e=>this.appendBlocker(e)));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then((t=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(e){e.forEach((e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;s&&!s.updating&&this.shiftAndExecuteNext(e)}))}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((e,t)=>e+(this.isPending(this.tracks[t])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((e,[t])=>e+(t?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([e])=>e)).filter((e=>!!e))}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach((e=>{s.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},capLevelController:Ta,errorController:class extends ei{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Us.ERROR,this.onError,this),e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Us.ERROR,this.onError,this),e.off(Us.ERROR,this.onErrorOut,this),e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===qs?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===s?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if(null!=(s=e.details)&&s.hasKey(t))return!0;const i=e.audioGroups;if(i){return this.hls.allAudioTracks.filter((e=>i.indexOf(e.groupId)>=0)).some((e=>{var s;return null==(s=e.details)?void 0:s.hasKey(t)}))}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case Bs.FRAG_LOAD_ERROR:case Bs.FRAG_LOAD_TIMEOUT:case Bs.KEY_LOAD_ERROR:case Bs.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Bs.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=zr());case Bs.FRAG_GAP:case Bs.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Ur);case Bs.LEVEL_EMPTY_ERROR:case Bs.LEVEL_PARSING_ERROR:{var n;const e=t.parent===qs?t.level:i.loadLevel;t.details===Bs.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case Bs.LEVEL_LOAD_ERROR:case Bs.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case Bs.AUDIO_TRACK_LOAD_ERROR:case Bs.AUDIO_TRACK_LOAD_TIMEOUT:case Bs.SUBTITLE_LOAD_ERROR:case Bs.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=i.loadLevelObj;if(e&&(r.type===Vs&&e.hasAudioGroup(r.groupId)||r.type===Ws&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ur,void(t.errorAction.flags=Wr)}return;case Bs.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Ur,flags:qr});case Bs.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Bs.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Bs.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Ur,flags:jr});case Bs.BUFFER_ADD_CODEC_ERROR:case Bs.REMUX_ALLOC_ERROR:case Bs.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:i.loadLevel);return;case Bs.INTERNAL_EXCEPTION:case Bs.BUFFER_APPENDING_ERROR:case Bs.BUFFER_FULL_ERROR:case Bs.LEVEL_SWITCH_ERROR:case Bs.BUFFER_STALLED_ERROR:case Bs.BUFFER_SEEK_OVER_HOLE:case Bs.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=zr())}t.type===$s.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=zr())}getPlaylistRetryOrSwitchAction(e,t){const s=xr(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Nr(s,i,Cr(e),e.response))return{action:Hr,flags:Vr,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(e,t);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=xr(kr(e)?n:r,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(i&&(e.details!==Bs.FRAG_GAP&&i.fragmentError++,!Mr(e))){if(Nr(a,o,Cr(e),e.response))return{action:Hr,flags:Vr,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const t=e.details;i.loadError++,t===Bs.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===js&&t===Bs.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===Bs.BUFFER_ADD_CODEC_ERROR||t===Bs.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>i.audioCodec!==e)),p="video"===e.sourceBufferName&&(t===Bs.BUFFER_ADD_CODEC_ERROR||t===Bs.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t)),{type:m,groupId:v}=null!=(n=e.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(t===Bs.FRAG_GAP&&f===qs&&e.frag){const t=h[r].details;if(t){const s=wr(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(m===Vs&&s.hasAudioGroup(v)||m===Ws&&s.hasSubtitleGroup(v))continue;if(f===js&&null!=(a=i.audioGroups)&&a.some((e=>s.hasAudioGroup(e)))||f===zs&&null!=(o=i.subtitleGroups)&&o.some((e=>s.hasSubtitleGroup(e)))||g&&i.audioCodec===s.audioCodec||p&&i.codecSet===s.codecSet||!g&&i.codecSet!==s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:Ur,flags:Vr,nextAutoLevel:l}}return{action:Ur,flags:Wr}}onErrorOut(e,t){var s;switch(null==(s=t.errorAction)?void 0:s.action){case Br:break;case Ur:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Bs.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Vr:this.switchLevel(e,r);break;case qr:{const i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(s.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=fr[fr.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case jr:{const t=e.decryptdata;if(t){const i=this.hls.levels,r=i.length;for(let s=r;s--;){var n,a;if(this.variantHasKey(i[s],t))this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(n=i[s].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${gi(t.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${e.error})`),this.hls.removeLevel(s)}const o=e.frag;if(this.hls.levels.length<r)s.resolved=!0;else if(o&&o.type!==qs){const e=o.decryptdata;e&&!t.matches(e)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===Bs.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=ur(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${i} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(i))}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Us.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Us.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,r=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(Us.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Us.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!1,preserveManualLevelOnError:!1,certLoadPolicy:{default:el},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:el},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:ci,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!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,cmcdController:void 0,contentSteeringController:class extends ei{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Us.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Us.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===Ur&&s.flags===Wr){const e=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:s,pathwayId:i,type:n}=t.context;s&&e?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&e&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),t.details!==Bs.BUFFER_APPEND_ERROR||t.fatal?s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${Lr(i)} penalized: ${Lr(this.penalizedPathways)}`):s.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach((e=>{i-s[e]>3e5&&delete s[e]}));for(let i=0;i<e.length;i++){const r=e[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,On(t),this.hls.trigger(Us.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(t===Vs&&i[s].hasAudioGroup(e)||t===Ws&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach((e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new Xr(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=La(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Sr({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return h}));t.push(...o),_a(this.audioTracks,s,a,r),_a(this.subtitleTracks,i,a,r)}))}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(t);try{i=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(Us.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,s,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,r);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}},interstitialsController:void 0});function sl(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(sl):Object.keys(e).reduce(((t,s)=>(t[s]=sl(e[s]),t)),{}):e}function il(e,t){const s=e.loader;if(s!==Yo&&s!==Zo)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=Yo,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class rl extends sa{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(Us.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Us.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Us.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;da(s,"playing",this.onMediaPlaying),da(s,"waiting",this.onMediaWaiting),da(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(ca(s,"playing",this.onMediaPlaying),ca(s,"waiting",this.onMediaWaiting),ca(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(h)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Us.MEDIA_ENDED,{stalled:!1})));if(!na.getBuffered(n).length)return void(this.nudgeRetry=0);const d=na.bufferInfo(n,e,0),c=d.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const t=nl(this.hls.inFlightFragments,e),s=d.len>2,i=!c||t||c-e>2&&!u.getPartialFragment(e);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(d.len>0)&&!c)return;const t=Math.max(c,d.start||0)-e,s=!(null==f||!f.live)?2*f.targetduration:2,i=ol(e,u);if(t>0&&(t<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(Us.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}const S=na.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Us.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&e>i.end(0)){const s=na.bufferedInfo(na.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const s=na.timeRangesToArray(i),r=na.bufferedInfo(s,t,0).bufferedIndex;if(r>-1&&r<s.length-1){const t=na.bufferedInfo(s,e,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===t||t>r)&&n-i<1&&e-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${i} -> ${n} buffered index: ${t}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=ol(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=na.bufferInfo(this.media,e,0);this.hls.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=ol(s,n);if(h||null!=l&&l.live&&s<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=e.buffered,c=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const e=s.getFragAtPos(t,qs),r=s.getFragAtPos(i,qs);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Lr(e)})`);this.warn(i.message),t.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=null==(t=this.hls)?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=na.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,h=a.len>0&&a.len<1&&i.readyState<3,d=o-n;if(d>0&&(t||h)){if(d>r.maxBufferHole){let t=!1;if(0===n){const e=s.getAppendedFrag(0,qs);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(nl(this.hls.inFlightFragments,o))return 0;let t=!1,i=e.end;for(;i<o;){const e=ol(i,s);if(!e){t=!0;break}i+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,i.currentTime=t,null==e||!e.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),i={type:$s.MEDIA_ERROR,details:Bs.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?i.part=e:i.frag=e),this.hls.trigger(Us.ERROR,i)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=null==t?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:e.len,bufferInfo:e})}}}function nl(e,t){const s=al(e.main);if(s&&s.start<=t)return s;const i=al(e.audio);return i&&i.start<=t?i:null}function al(e){if(!e)return null;switch(e.state){case fa.IDLE:case fa.STOPPED:case fa.ENDED:case fa.ERROR:return null}return e.frag}function ol(e,t){return t.getAppendedFrag(e,qs)||t.getPartialFragment(e)}function ll(e,t){let s;try{s=new Event("addtrack")}catch(e){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=e,t.dispatchEvent(s)}function hl(e,t,s,i){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,s){const i=[],r=function(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),t<e[i].startTime)n=i-1;else{if(!(t>e[i].startTime&&r<s))return i;r=i+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(e.cues,t,s);for(let t=0;t<r.length;t++)i&&!i(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function dl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function cl(e,t,s,i,r){let n=new e(t,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new e(t,s,Lr(r?Zs({type:r},i):i))}return n}const ul=(()=>{const e=dl();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class fl{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Us.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Us.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Us.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Us.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Us.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Us.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Us.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Us.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,!1===(null==(s=t.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&function(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues)for(let s=e.cues.length;s--;)t&&e.cues[s].removeEventListener("enter",t),e.removeCue(e.cues[s]);"disabled"===s&&(e.mode=s)}(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if("metadata"===s.kind&&"id3"===s.label)return ll(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=dl();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===Ja.emsg&&!s||!i)continue;const a=Ka(r[e].data),o=r[e].pts;let l=o+r[e].duration;l>ul&&(l=ul);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!Ya(s)){this.updateId3CueEnds(o,t);const e=cl(n,o,l,s,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===t&&r.startTime<e&&r.endTime===ul&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===i?e=>e.type===Ja.audioId3&&o:"video"===i?e=>e.type===Ja.emsg&&a:e=>e.type===Ja.audioId3&&o||e.type===Ja.emsg&&a,hl(r,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=dl();if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,h=Object.keys(l);let d=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.cues)&&c.length){const e=Object.keys(d).filter((e=>!h.includes(e)));for(let t=e.length;t--;){var u;const s=e[t],i=null==(u=d[s])?void 0:u.cues;delete d[s],i&&Object.keys(i).forEach((e=>{const t=i[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(e){}}}))}}else d=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==h.length&&Os(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<h.length;e++){const t=h[e],s=l[t],i=s.startTime,r=d[t],n=(null==r?void 0:r.cues)||{};let o=(null==r?void 0:r.durationKnown)||!1,c=ul;const{duration:u,endDate:f}=s;if(f&&null!==u)c=i+u,o=!0;else if(s.endOnNext&&!o){const e=h.reduce(((e,t)=>{if(t!==s.id){const i=l[t];if(i.class===s.class&&i.startDate>s.startDate&&(!e||s.startDate<e.startDate))return i}return e}),null);e&&(c=e.startTime,o=!0)}const p=Object.keys(s.attr);for(let e=0;e<p.length;e++){const l=p[e];if("ID"===(g=l)||"CLASS"===g||"CUE"===g||"START-DATE"===g||"DURATION"===g||"END-DATE"===g||"END-ON-NEXT"===g)continue;const h=n[l];if(h)!o||null!=r&&r.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=c):h.endTime=c;else if(a){let e=s.attr[l];Qr(l)&&(e=pi(e));const r=cl(a,i,c,{key:l,data:e},Ja.dateRange);r&&(r.id=t,this.id3Track.addCue(r),n[l]=r)}}d[t]={cues:n,dateRange:s,durationKnown:o}}var g}}}class gl{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Us.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Us.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Us.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Us.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===Bs.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class pl extends $n{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Us.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Us.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Us.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Us.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Us.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Us.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{const t=e.attrs;let{audioCodec:h,videoCodec:d}=e;h&&(e.audioCodec=h=or(h,s)||void 0),d&&(d=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const s=t[e].split(".");s.length>2&&"avc1"===s[0]&&(t[e]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}(d));const{width:c,height:u,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!d),l||(l=!!h),g||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:p,"FRAME-RATE":m,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":S}=t,T=`${`${y||"."}-`}${e.bitrate}-${E}-${m}-${p}-${S}-${v}`;if(r[T])if(r[T].uri===e.url||e.attrs["PATHWAY-ID"])r[T].addGroupId("audio",t.AUDIO),r[T].addGroupId("text",t.SUBTITLES);else{const t=n[T]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=this.createLevel(e);r[T]=s,i.push(s)}else{const t=this.createLevel(e);r[T]=t,n[T]=1,i.push(t)}})),this.filterAndSortMediaOptions(i,t,a,o,l)}createLevel(e){const t=new Sr(e),s=e.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(e.message),t.supportedResult=di.getUnsupportedResult(e,[])}return t}isAudioSupported(e){return er(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return er(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let a=[],o=[],l=e;const h=(null==(n=t.stats)?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter((({videoCodec:e,videoRange:t,width:s,height:i})=>{return(!!e||!(!s||!i))&&(!!(r=t)&&gr.indexOf(r)>-1);var r}))),0===l.length)return Promise.resolve().then((()=>{if(this.hls){let e="no level with compatible codecs found in manifest",s=e;t.levels.length&&(s=`one or more CODECS in variant not supported: ${Lr(t.levels.map((e=>e.attrs.CODECS)).filter(((e,t,s)=>s.indexOf(e)===t)))}`,this.warn(s),e+=` (${s})`);const i=new Error(e);this.hls.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:s})}})),void(h.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter((e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),ml(a)),t.subtitles&&(o=t.subtitles,ml(o));const d=l.slice(0);l.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return gr.indexOf(e.videoRange)-gr.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=ir(e.videoCodec),i=ir(t.videoCodec);if(s!==i)return i-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=rr(e.codecSet),i=rr(t.codecSet);if(s!==i)return i-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let c=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length))for(let e=0;e<d.length;e++)if(d[e].pathwayId===l[0].pathwayId){c=d[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===c){var u;this._firstLevel=e;const t=c.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=r&&!i,g=this.hls.config,p=!(!g.audioStreamController||!g.audioTrackController),m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:p&&!f&&a.some((e=>!!e.url))};h.end=performance.now(),this.hls.trigger(Us.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(Us.ERROR,{type:$s.OTHER_ERROR,details:Bs.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:s,reason:s.message}),i)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(Us.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter((e=>-1!==t.indexOf(e)));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===Hs&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===qs){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(i,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${s}`),this.hls.trigger(Us.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter(((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));On(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(Us.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Us.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function ml(e){const t={};e.forEach((e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++}))}const vl="1.6.15",yl={};let El=0;class Sl{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=El++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Us.ERROR,{type:$s.OTHER_ERROR,details:Bs.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===Us.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Pa,this.observer.on(Us.FRAG_DECRYPTED,n),this.observer.on(Us.ERROR,n);const a=cr(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=yl[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return yl[e]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=yl[vl];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return yl[vl]=i,i}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Lr(r)})}catch(i){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Vo(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Vo(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=El++;const t=this.hls.config,s=cr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:Lr(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=yl[e||vl];if(t&&1==t.clientCount--){const{worker:s,objectURL:i}=t;delete yl[e||vl],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,p=r.decryptdata,m=this.frag,v=!(m&&r.cc===m.cc),y=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,S=this.part?l.part-this.part.index:-1,T=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),_=!y&&(1===E||0===E&&(1===S||T&&S<=0)),L=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!S&&_||(n.stats.parsing.start=L);const b=!(m&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),R=new zo(v,_,o,y,g,b);if(!_||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===qs?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${_}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${b}`);const e=new jo(s,i,t,a,h);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,p,l,R);qo(t)?t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);qo(t)?t.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(Us.ERROR,{type:$s.MEDIA_ERROR,details:Bs.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function Tl(){return self.SourceBuffer||self.WebKitSourceBuffer}function _l(){if(!ui())return!1;const e=Tl();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Ll extends ga{constructor(e,t,s){super(e,t,s,"stream-controller",qs),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!Os(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const s=this.getFwdBufferInfoAtPos(e,t,qs,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Us.LEVEL_LOADING,this.onLevelLoading,this),e.on(Us.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Us.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Us.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Us.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Us.BUFFER_CREATED,this.onBufferCreated,this),e.on(Us.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Us.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Us.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Us.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Us.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Us.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Us.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Us.BUFFER_CREATED,this.onBufferCreated,this),e.off(Us.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Us.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Us.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=fa.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=fa.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case fa.WAITING_LEVEL:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=fa.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=fa.IDLE;break}break}case fa.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===fa.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(null===t||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(Us.BUFFER_EOS,e),void(this.state=fa.ENDED)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===fa.WAITING_LEVEL||this.waitForLive(n))return this.level=r,this.state=fa.WAITING_LEVEL,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&bi(u)&&this.fragmentTracker.getState(u)!==Hn){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?Si:Ti,t=(e===Ti?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,qs)}u=this.getNextFragmentLoopLoading(u,l,a,qs,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Bn||i===Gn?bi(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,qs)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,i=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case fa.KEY_LOADING:case fa.FRAG_LOADING:case fa.FRAG_LOADING_WAITING_RETRY:case fa.PARSING:case fa.PARSED:this.state=fa.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;da(s,"playing",this.onMediaPlaying),da(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(ca(s,"playing",this.onMediaPlaying),ca(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Us.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let e=0;e<t.levels.length;e++){const r=t.levels[e].audioCodec;r&&(s=s||-1!==r.indexOf("mp4a.40.2"),i=i||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var e;const t=Tl();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==fa.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=fa.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==fa.FRAG_LOADING&&this.state!==fa.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,d),this.hls.trigger(Us.LEVEL_UPDATED,{details:a,level:n}),this.state===fa.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=fa.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=na.bufferInfo(s,i,0);if(null==(l=e.buffered)||!l.length)return void(s.currentTime=i);if(e.start<=r)return void(s.currentTime=i);const{nextStart:t}=na.bufferedInfo(e.buffered,r,0);t&&(s.currentTime=t)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Sl(this.hls,qs,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,p=new ia(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,p,m)}onAudioTrackSwitching(e,t){const s=this.hls,i=0!==this.altAudio;if(Ar(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(Us.BUFFER_FLUSHED,(()=>{this.hls&&this.hls.trigger(Us.AUDIO_TRACK_SWITCHED,t)})),void s.trigger(Us.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(Us.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Ar(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const e in s){const t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){const t=s[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===qs;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===fa.PARSED&&(this.state=fa.IDLE));const e=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),bi(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&na.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=fa.ERROR;else switch(t.details){case Bs.FRAG_GAP:case Bs.FRAG_PARSING_ERROR:case Bs.FRAG_DECRYPT_ERROR:case Bs.FRAG_LOAD_ERROR:case Bs.FRAG_LOAD_TIMEOUT:case Bs.KEY_LOAD_ERROR:case Bs.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(qs,t);break;case Bs.LEVEL_LOAD_ERROR:case Bs.LEVEL_LOAD_TIMEOUT:case Bs.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==fa.WAITING_LEVEL||(null==(s=t.context)?void 0:s.type)!==Hs||(this.state=fa.IDLE);break;case Bs.BUFFER_ADD_CODEC_ERROR:case Bs.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Bs.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Bs.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=fa.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Si||!this.altAudio){const e=(t===Ti?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,qs),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=na.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((e=>{const{hls:s}=this,i=null==e?void 0:e.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=fa.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(Us.FRAG_LOADED,e),i.bitrateTest=!1})).catch((t=>{this.state!==fa.STOPPED&&this.state!==fa.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:h,text:d,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=fa.PARSING,u){const e=u.tracks;if(e){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,i,r),s.trigger(Us.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:t,tracks:e})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(Os(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:e},s.trigger(Us.INIT_PTS_FOUND,{frag:a,id:t,initPTS:i,timescale:n,trackId:e})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,s=!e||a.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:i,startDTS:n,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:e,endPTS:i,startDTS:n,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,i,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,e,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,t||s)}else{if(!t&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[Si]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(Si,e,t,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};s.trigger(Us.FRAG_PARSING_METADATA,e)}if(f&&d){const e={id:t,frag:a,details:f,samples:d.samples};s.trigger(Us.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${bi(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==fa.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=t;if(r){const s=e.audioCodec;let i=lr(r.codec,s);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=qs,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=qs;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(Us.BUFFER_CODECS,t),!this.hls)return;o.forEach((e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(Us.BUFFER_APPENDING,{type:e,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,qs)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=fa.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(na.isBuffered(e,s)?t=this.getAppendedFrag(s):na.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,s=t.level;e&&t.sn===e.sn&&e.level===s||(this.fragPlaying=t,this.hls.trigger(Us.FRAG_CHANGED,{frag:t}),e&&e.level===s||this.hls.trigger(Us.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return Os(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(Os(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?wr(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const i=e+1e3*(t-s.start);return new Date(i)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class bl extends ei{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=Bs.KEY_LOAD_ERROR,s,i,r){return new ta({type:$s.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var s,i;const r=e.decryptdata;if(!r){const s=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,Bs.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,Bs.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=Rl(r);let o=this.keyIdToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(i=o)&&i.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then((t=>{const{keyInfo:s}=t;return r.key=s.decryptdata.key,{frag:e,keyInfo:s}}))}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+gi(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,Bs.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){const s=function(e){const t=[];return Wi(e,(e=>t.push(e.subarray(8,24)))),t}(t.initSegment.data);if(s.length){let t=s[0];t.some((e=>0!==e))?(this.log(`Using keyId found in init segment ${gi(t)}`),ln.setKeyIdForUri(e.decryptdata.uri,t)):(t=ln.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${gi(t)}`)),e.decryptdata.keyId=t}}if(!e.decryptdata.keyId&&!bi(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then((t=>(e.mediaKeySessionContext=t,s)))).catch((s=>{throw e.keyLoadPromise=null,"data"in s&&(s.data.frag=t),s}))}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=new(0,s.loader)(s);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{const{frag:a,keyInfo:o}=s,l=Rl(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,Bs.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,Bs.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),i,Zs({url:a.url,data:void 0},e)))},onTimeout:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,Bs.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,Bs.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,h)}))}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=Rl(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Rl(e){return e.uri}function Al(e){const{type:t}=e;switch(t){case Vs:return js;case Ws:return zs;default:return qs}}function Pl(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}class wl{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Us.LEVEL_LOADING,this.onLevelLoading,this),e.on(Us.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Us.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Us.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Us.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Us.LEVEL_LOADING,this.onLevelLoading,this),e.off(Us.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Us.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Us.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=new(s||i)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Gs,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Hs,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Vs,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Ws,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[Hs];if(s){const e=s.context;e&&!t.levels.some((t=>t===e.levelOrTrack))&&(s.abort(),delete this.loaders[Hs])}}load(e){var t;const s=this.hls.config;let i,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,s=r.context;if(s&&s.levelOrTrack===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(i=e.type===Gs?s.manifestLoadPolicy.default:Qs({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Os(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===Hs&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Vs&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Ws&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);i=Qs({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;t.parsing.start=performance.now(),gn.isMediaPlaylist(n)||s.type!==Gs?this.handleTrackOrLevelPlaylist(e,t,s,i||null,r):this.handleMasterPlaylist(e,t,s,i)},onError:(e,t,s,i)=>{this.handleNetworkError(t,s,!1,e,i)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,a=Pl(e,s),o=gn.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,o.playlistParsingError,i,t);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,h.forEach((e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];er(a,"audio",s)?(e.audioCodec=i=i?`${i},${a}`:a,Ji.audio[i.substring(0,4)]=2,t.splice(n,1)):er(a,"video",s)&&(e.videoCodec=r=r?`${r},${a}`:a,Ji.video[r.substring(0,4)]=2,t.splice(n,1))}}}));const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=gn.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Xr({}),bitrate:0,url:""}))}r.trigger(Us.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=Pl(e,s),d=Os(o)?o:Os(a)?a:0,c=Al(s),u=gn.parseLevelPlaylist(e.data,h,d,c,0,this.variableList);if(l===Gs){const e={attrs:new Xr({}),bitrate:0,details:u,name:"",url:h};u.requestScheduled=t.loading.start+Cn(u,0),n.trigger(Us.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(Us.ERROR,{type:$s.NETWORK_ERROR,details:Bs.MANIFEST_PARSING_ERROR,fatal:t.type===Gs,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Hs?n+=`: ${e.level} id: ${e.id}`:e.type!==Vs&&e.type!==Ws||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=Bs.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Gs:o=s?Bs.MANIFEST_LOAD_TIMEOUT:Bs.MANIFEST_LOAD_ERROR,l=!0;break;case Hs:o=s?Bs.LEVEL_LOAD_TIMEOUT:Bs.LEVEL_LOAD_ERROR,l=!1;break;case Vs:o=s?Bs.AUDIO_TRACK_LOAD_TIMEOUT:Bs.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Ws:o=s?Bs.SUBTITLE_TRACK_LOAD_TIMEOUT:Bs.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const d={type:$s.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};if(i){const s=(null==t?void 0:t.url)||e.url;d.response=Zs({url:s,data:void 0},i)}this.hls.trigger(Us.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:d,groupId:c,deliveryDirectives:u}=i,f=Pl(t,i),g=Al(i);let p="number"==typeof i.level&&g===qs?l:void 0;const m=e.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(Us.ERROR,{type:$s.NETWORK_ERROR,details:Bs.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:i,level:p,parent:g,networkDetails:r,stats:s});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Gs:case Hs:if(p)if(h){if(h!==a.levels[p]){const e=a.levels.indexOf(h);e>-1&&(p=e)}}else p=0;a.trigger(Us.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:p||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===Gs});break;case Vs:a.trigger(Us.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case Ws:a.trigger(Us.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u})}else{const n=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(Us.ERROR,{type:$s.NETWORK_ERROR,details:Bs.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:i,level:p,parent:g,networkDetails:r,stats:s})}}}const Il={supported:!1,smooth:!1,powerEfficient:!1},Dl={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Cl(e,t,s,i={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!s)return Promise.resolve(Dl);const n=[],a=function(e){var t;const s=null==(t=e.videoCodec)?void 0:t.split(","),i=Ml(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map((e=>{const t={contentType:sr(dr(e),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t})):[]}(e),o=a.length,l=function(e,t,s){var i;const r=null==(i=e.audioCodec)?void 0:i.split(","),n=Ml(e);if(r&&e.audioGroups)return e.audioGroups.reduce(((e,i)=>{var a;const o=i?null==(a=t.groups[i])?void 0:a.tracks:null;return o?o.reduce(((e,t)=>{if(t.groupId===i){const i=parseFloat(t.channels||"");r.forEach((t=>{const r={contentType:sr(t,"audio"),bitrate:s?kl(t,n):n};i&&(r.channels=""+i),e.push(r)}))}return e}),e):e}),[]);return[]}(e,t,o>0),h=l.length;for(let e=o||1*h||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),h){t.audio=l[e%h];const s=t.audio.bitrate;t.video&&s&&(t.video.bitrate-=s)}n.push(t)}if(r){const e=navigator.userAgent;if(r.split(",").some((e=>zi(e)))&&Qi())return Promise.resolve(function(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Il],error:e}}(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map((e=>{const t=function(e){let t="";const{audio:s,video:i}=e;if(i){t+=`${ur(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(s){t+=`${i?"_":""}${ur(s.contentType)}_c${s.channels}`}return t}(e);return i[t]||(i[t]=s.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:n,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e})))}function kl(e,t){if(t<=1)return 1;let s=128e3;return"ec-3"===e?s=768e3:"ac-3"===e&&(s=64e4),Math.min(t/2,s)}function Ml(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}class xl{static get version(){return vl}static isMSESupported(){return _l()}static isSupported(){return function(){if(!_l())return!1;const e=ui();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(sr(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(sr(t,"audio")))))}()}static getMediaSource(){return ui()}static get Events(){return Us}static get MetadataSchema(){return Ja}static get ErrorTypes(){return $s}static get ErrorDetails(){return Bs}static get DefaultConfig(){return xl.defaultConfig?xl.defaultConfig:tl}static set DefaultConfig(e){xl.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Pa,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,s){const i=ii();if("object"==typeof console&&!0===e||"object"==typeof e){const r=["debug","log","info","warn","error"];r.forEach((t=>{i[t]=ri(t,e,s)}));try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch(e){return ii()}r.forEach((t=>{ni[t]=ri(t,e)}))}else Qs(ni,i);return i}(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=function(e,t,s){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");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=sl(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach((s=>{const r=`${e}Loading${s}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=i[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Lr(t[n])}`)})),Zs(Zs({},i),t)}(xl.DefaultConfig,e,t);this.userConfig=e,s.progressive&&il(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=s,l=new a(this),h=this.abrController=new i(this),d=new Vn(this),c=s.interstitialsController,u=c?this.interstitialsController=new c(this,xl):null,f=this.bufferController=new r(this,d),g=this.capLevelController=new n(this),p=new o(this),m=new wl(this),v=s.contentSteeringController,y=v?new v(this):null,E=this.levelController=new pl(this,y),S=new fl(this),T=new bl(this.config,this.logger),_=this.streamController=new Ll(this,d,T),L=this.gapController=new rl(this,d);g.setStreamController(_),p.setStreamController(_);const b=[m,E,_];u&&b.splice(1,0,u),y&&b.splice(1,0,y),this.networkControllers=b;const R=[h,f,L,g,p,S,d];this.audioTrackController=this.createController(s.audioTrackController,b);const A=s.audioStreamController;A&&b.push(this.audioStreamController=new A(this,d,T)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);const P=s.subtitleStreamController;P&&b.push(this.subtititleStreamController=new P(this,d,T)),this.createController(s.timelineController,R),T.emeController=this.emeController=this.createController(s.emeController,R),this.cmcdController=this.createController(s.cmcdController,R),this.latencyController=this.createController(gl,R),this.coreComponents=R,b.push(l);const w=l.onErrorOut;"function"==typeof w&&this.on(Us.ERROR,w,l),this.on(Us.MANIFEST_LOADED,m.onManifestLoaded,m)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const s=e===Us.ERROR;this.trigger(Us.ERROR,{type:$s.OTHER_ERROR,details:Bs.INTERNAL_EXCEPTION,fatal:s,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Us.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(Us.ERROR,{type:$s.OTHER_ERROR,details:Bs.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(Us.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Us.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(Us.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=yi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Us.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((e=>{e.resumeBuffering&&e.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((e=>{e.pauseBuffering&&e.pauseBuffering()})))}get inFlightFragments(){const e={[qs]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[js]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[zs]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?s:3&s|8).toString(16)}))}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return fr.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let t=i;t--;){const i=e[t].attrs["HDCP-LEVEL"];if(i&&i<=s)return t}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Cl(e,Rr(t),navigator.mediaCapabilities)}}xl.defaultConfig=void 0;di.KeySystemFormats,di.KeySystems,di.SubtitleStreamController,di.TimelineController,di.requestMediaKeySystemAccess;const Ol={maxBufferLength:12},Fl={maxBufferLength:40};class Nl extends xl{static get P2PEvents(){return xs.Events}static get P2pEngine(){return xs}constructor(e={}){let t=e.p2pConfig||{};const s=!1===t.live?Fl:Ol;let i=JSON.parse(JSON.stringify(s));i.maxBufferSize=0;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},xs.isSupported()&&(this._p2pEngine=new xs({...t,hlsjsInstance:this}),this._p2pEngine.on(xs.Events.RESTART_P2P,this._restartEvent)),this.on(xl.Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(xs.Events.RESTART_P2P,this._restartEvent),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.removeAllListeners(xs.Events.RESTART_P2P),this._p2pEngine.once(xs.Events.RESTART_P2P,(()=>{this.disableP2P()})))}}Nl.engineVersion=xs.version,Nl.protocolVersion=xs.protocolVersion,Nl.WEBRTC_SUPPORT=xs.isSupported();const $l=Nl})(),i=i.default})()));
|
|
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()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,s="object"==typeof Reflect?Reflect:null,i=s&&"function"==typeof s.apply?s.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)};t=s&&"function"==typeof s.ownKeys?s.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(s,i){function r(s){e.removeListener(t,n),i(s)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",r),s([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,s){"function"==typeof e.on&&p(e,"error",t,s)}(e,r,{once:!0})}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var 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?n.defaultMaxListeners:e._maxListeners}function h(e,t,s,i){var r,n,a,h;if(o(s),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),n=e._events),a=n[t]),void 0===a)a=n[t]=s,++e._eventsCount;else if("function"==typeof a?a=n[t]=i?[s,a]:[a,s]:i?a.unshift(s):a.push(s),(r=l(e))>0&&a.length>r&&!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 c(e,t,s){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},r=d.bind(i);return r.listener=s,i.wrapFn=r,r}function u(e,t,s){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?s?[r.listener||r]:[r]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(r):g(r,r.length)}function f(e){var t=this._events;if(void 0!==t){var s=t[e];if("function"==typeof s)return 1;if(void 0!==s)return s.length}return 0}function g(e,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=e[i];return s}function p(e,t,s,i){if("function"==typeof e.on)i.once?e.once(t,s):e.on(t,s);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(n){i.once&&e.removeEventListener(t,r),s(n)}))}}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),n.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var r="error"===e,n=this._events;if(void 0!==n)r=r&&void 0===n.error;else if(!r)return!1;if(r){var 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=n[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(s=0;s<h;++s)i(d[s],this,t)}return!0},n.prototype.addListener=function(e,t){return h(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return h(this,e,t,!0)},n.prototype.once=function(e,t){return o(t),this.on(e,c(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,c(this,e,t)),this},n.prototype.removeListener=function(e,t){var s,i,r,n,a;if(o(t),void 0===(i=this._events))return this;if(void 0===(s=i[e]))return this;if(s===t||s.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(r=-1,n=s.length-1;n>=0;n--)if(s[n]===t||s[n].listener===t){a=s[n].listener,r=n;break}if(r<0)return this;0===r?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,r),1===s.length&&(i[e]=s[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,s,i;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var r,n=Object.keys(s);for(i=0;i<n.length;++i)"removeListener"!==(r=n[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},n.prototype.listeners=function(e){return u(this,e,!0)},n.prototype.rawListeners=function(e){return u(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=a.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=a.normalizePath(r.path),a.buildURLFromParts(r)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(c)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=s.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=s.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()},424:(e,t)=>{"use strict";t.h=r;var s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=r.prototype,t}function r(e,t,s){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return n(e,t,s)}function n(e,t,s){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!r.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var s=0|d(e,t),n=i(s),a=n.write(e,t);a!==s&&(n=n.slice(0,a));return n}(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(v(e,ArrayBuffer)||e&&v(e.buffer,ArrayBuffer))return function(e,t,s){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(s||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,t):new Uint8Array(e,t,s);return i.__proto__=r.prototype,i}(e,t,s);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return r.from(n,t,s);var a=function(e){if(r.isBuffer(e)){var t=0|h(e.length),s=i(t);return 0===s.length||e.copy(s,0,0,t),s}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?i(0):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 r.from(e[Symbol.toPrimitive]("string"),t,s);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function 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),s=i(t),r=0;r<t;r+=1)s[r]=255&e[r];return s}function h(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function d(e,t){if(r.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||v(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var s=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===s)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":return m(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;default:if(n)return i?-1:m(e).length;t=(""+t).toLowerCase(),n=!0}}function c(e,t,s,i){s=Number(s)||0;const r=e.length-s;i?(i=Number(i))>r&&(i=r):i=r;const n=t.length;let a;for(i>n/2&&(i=n/2),a=0;a<i;++a){const i=parseInt(t.substr(2*a,2),16);if(y(i))return a;e[s+a]=i}return a}function u(e,t,s,i){return p(m(t,e.length-s),e,s,i)}function f(e,t,s,i){return p(function(e){const t=[];for(let s=0;s<e.length;++s)t.push(255&e.charCodeAt(s));return t}(t),e,s,i)}function g(e,t,s,i){return p(function(e,t){let s,i,r;const n=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)s=e.charCodeAt(a),i=s>>8,r=s%256,n.push(r),n.push(i);return n}(t,e.length-s),e,s,i)}function p(e,t,s,i){let r;for(r=0;r<i&&!(r+s>=t.length||r>=e.length);++r)t[r+s]=e[r];return r}function m(e,t){var s;t=t||1/0;for(var i=e.length,r=null,n=[],a=0;a<i;++a){if((s=e.charCodeAt(a))>55295&&s<57344){if(!r){if(s>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&n.push(239,191,189);continue}r=s;continue}if(s<56320){(t-=3)>-1&&n.push(239,191,189),r=s;continue}s=65536+(r-55296<<10|s-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,s<128){if((t-=1)<0)break;n.push(s)}else if(s<2048){if((t-=2)<0)break;n.push(s>>6|192,63&s|128)}else if(s<65536){if((t-=3)<0)break;n.push(s>>12|224,s>>6&63|128,63&s|128)}else{if(!(s<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(s>>18|240,s>>12&63|128,s>>6&63|128,63&s|128)}}return n}function v(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),r.from=function(e,t,s){return n(e,t,s)},r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,r.alloc=function(e,t,s){return function(e,t,s){return a(e),e<=0?i(e):void 0!==t?"string"==typeof s?i(e).fill(t,s):i(e).fill(t):i(e)}(e,t,s)},r.allocUnsafe=function(e){return o(e)},r.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==r.prototype},r.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return r.alloc(0);var s;if(void 0===t)for(t=0,s=0;s<e.length;++s)t+=e[s].length;var i=r.allocUnsafe(t),n=0;for(s=0;s<e.length;++s){var a=e[s];if(v(a,Uint8Array)&&(a=r.from(a)),!r.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,n),n+=a.length}return i},r.byteLength=d,r.prototype._isBuffer=!0,r.prototype.copy=function(e,t,s,i){if(!r.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<s&&(i=s),i===s)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-s&&(i=e.length-t+s);var n=i-s;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,s,i);else if(this===e&&s<t&&t<i)for(var a=n-1;a>=0;--a)e[a+t]=this[a+s];else Uint8Array.prototype.set.call(e,this.subarray(s,i),t);return n},r.prototype.write=function(e,t,s,i){if(void 0===t)i="utf8",s=this.length,t=0;else if(void 0===s&&"string"==typeof t)i=t,s=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(s)?(s>>>=0,void 0===i&&(i="utf8")):(i=s,s=void 0)}const r=this.length-t;if((void 0===s||s>r)&&(s=r),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return c(this,e,t,s);case"utf8":case"utf-8":return u(this,e,t,s);case"ascii":case"latin1":case"binary":return f(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,s);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}}},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var s={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return s.isAndroid()||s.isAndroidWebView()?t.ANDROID_WEB:s.isIOS()||s.isIpad()||s.isIOSWebView()?t.IOS_WEB:s.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!n(r("os "))&&!n(r("android[/ ]"))},isIOS:function(){return n(r("os "))},isIpad:function(){return i().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return n(r("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return s.isAndroid()||s.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=i();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=i();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return s.isAndroidWebView()||s.isIOSWebView()},device:t,getBrowser:function(){return s.isX5()?"X5":s.isAndroidWebView()?"Android-WebView":s.isIOSWebView()?"iOS-WebView":s.isChrome()?"Chrome":s.isFirefox()?"Firefox":s.isIpadSafari()?"iPad-Safari":s.isIOSSafari()?"iPhone-Safari":s.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function r(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=s}},t={};function s(i){var r=t[i];if(void 0!==r)return r.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,s),n.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";s.d(i,{default:()=>Fl});const e={DC_SIGNAL:"SIGNAL",DC_SIGNAL_BATCH:"SIGNAL_BATCH",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_DISCONNECT:"DISCONNECT",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",BM_FATAL_ERROR:"BM_FATAL_ERROR",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PROGRESS:"SYN_PROGRESS",MEDIA_REBUFFER:"MEDIA_REBUFFER"},t={...e,SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_GET_MEDIA:"SW_GET_MEDIA",SW_DEBUG:"SW_DEBUG",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED"};var r=s(415),n=s.n(r),a=s(424),o=s(558),l=s.n(o);const h="__PROXY_IDENTIFIER__";const d={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},c=64e3;function u(){return!0}function f(e){return new URL(location.href).searchParams.get(e)}function g(e,t,s){const i=new URL(e);return i.searchParams.append(t,s),i.href}function p(){return Math.floor(Date.now()/1e3)}function m(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function v(e){return new Promise((t=>setTimeout(t,e)))}function y(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function E(e){const t=a.h.from(e),s=new a.h(e.byteLength);return t.copy(s),s}function S(){return location.protocol.startsWith("https")}function T(e,t,s){if(e.size<=t)return;const i=[...e.keys()];do{const t=i.shift();s&&s(e.get(t)),e.delete(t)}while(e.size>t)}function _(e,t){if(e.size<=t)return;const s=[...e.values()];do{e.delete(s.shift())}while(e.size>t)}function L(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function b(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const s=Number(t[0]),i=t[1]?Number(t[1]):-1;return{rangeStart:s,rangeEnd:i>=0?i+1:void 0}}function R(e){return e.split("?")[0]}function A(){let e=new Date,t=e.getHours(),s=e.getMinutes(),i=e.getSeconds(),r=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${r}`}function P(e){return e&&"function"==typeof e}function w(e,t,s,i,r,n){const{sn:a,seg_id:o,size:l,level:h}=s;e.sendPartialBuffer(s,i,{from:r,incompletes:n})&&(e.bitset.add(a,h,o,d.COMPLETE,l),i.length<s.attachments?function(e,t,s){e.addStreamListener(s,t.remotePeerId,((e,s,i,r,n)=>{i?t.sendMsgPieceAbort(r,s,!0):t.uploading&&t.send(r),n&&(t.uploading=!1)}))}(t,e,!!s.reverse):e.uploading=!1)}const I=e=>0===m(0,1)?[null,e]:[e,null];function D(e,t,s){return 1===e.length?t.length>=1&&s.length>=1?t[0].weight>s[0].weight?[t[0],e[0]]:[e[0],s[0]]:t.length>=1?[t[0],e[0]]:s.length>=1?[e[0],s[0]]:I(e[0]):[t.length>=1?t[0]:null,s.length>=1?s[0]:null]}function C(){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}}}async function k(e){if(crypto.subtle)try{const t=await crypto.subtle.digest("SHA-256",e),s=String.fromCharCode.apply(null,new Uint8Array(t));return btoa(s)}catch(e){}}function M(e,t,s){if(!t)return{message:e,stack:"",filename:s};let i="";if("string"==typeof t)i=t;else if(t.message)i=t.message;else if(t.error&&t.error.message)i=t.error.message;else if(t.reason&&t.reason.message)i=t.reason.message;else try{i=String(t)}catch(e){}let r="";return r=t.stack?t.stack:t.error&&t.error.stack?t.error.stack:t.reason&&t.reason.stack?t.reason.stack:"",{message:i.trim()||e,stack:r.trim()||JSON.stringify(t),filename:s}}function x(e){const t=[...e];for(let e=t.length-1;e>0;e--){const s=Math.floor(Math.random()*(e+1));[t[e],t[s]]=[t[s],t[e]]}return t}class O{constructor(e,t){this.target=t,this.type=e}}class F extends O{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class N extends O{constructor(e=1e3,t="",s){super("close",s),this.code=e,this.reason=t,this.wasClean=!0}}const $=()=>{if("undefined"!=typeof WebSocket)return WebSocket},B={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class U{constructor(e,t,s={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=s,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return U.CONNECTING}get OPEN(){return U.OPEN}get CLOSING(){return U.CLOSING}get CLOSED(){return U.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?U.CLOSED:U.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws&&this._ws.readyState!==this.CLOSED&&this._ws.close(e,t)}reconnect(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()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._ws.send(e);else{const{maxEnqueuedMessages:t=B.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&this._messageQueue.push(e)}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const s of t)this._callEventListener(e,s);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=B.reconnectionDelayGrowFactor,minReconnectionDelay:t=B.minReconnectionDelay,maxReconnectionDelay:s=B.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=t*Math.pow(e,this._retryCount-1),i>s&&(i=s)),i}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=B.maxRetries,connectionTimeout:t=B.connectionTimeout,WebSocket:s=$()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(i=s)||!i||2!==i.CLOSING)throw Error("No valid WebSocket class provided");var i;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new s(e,this._protocols):new s(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new F(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new F(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new N(e,t,this))}catch(e){}}}_acceptOpen(){this._retryCount=0}_callEventListener(e,t){"handleEvent"in t?t.handleEvent(e):t(e)}_handleOpen(e){const{minUptime:t=B.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout((()=>this._acceptOpen()),t),this._ws.binaryType=this._binaryType,this._messageQueue.forEach((e=>this._ws.send(e))),this._messageQueue=[],this.onopen&&this.onopen(e),this._listeners.open.forEach((t=>this._callEventListener(e,t)))}_handleMessage(e){this.onmessage&&this.onmessage(e),this._listeners.message.forEach((t=>this._callEventListener(e,t)))}_handleError(e){this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._listeners.error.forEach((t=>this._callEventListener(e,t))),this._connect()}_handleClose(e){this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this._listeners.close.forEach((t=>this._callEventListener(e,t)))}_removeListeners(){this._ws&&(this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const G={debug:3,info:4,warn:5,error:6};class H{constructor(e,t,s,i){this.wsAddr=`${e}?app=${t}&id=${s}&v=${i}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:m(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new U(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const s=G[e];this._ws.send(JSON.stringify({records:[{level:s,text:`${A()}: ${t}`}]}))}sendBatch(e){const t=[];for(let s of e)t.push({level:G[s.levelKey],text:s.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const V={debug:0,info:1,warn:2,error:3,none:4};const W=class{constructor(e,t){this.logLevel=e,this.onlineDebug=!1,this.logCache=[],this.app=t;try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),(e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}})("SW_DEBUG")&&(this.logLevel="debug"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in V||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in V)this[e]=console[e];this._hookLogFunc(((e,t)=>{this.logUploader&&this.logUploader.send(e,t)}))}enableReport(e){this.reportUrl=e,this._hookLogFunc(((e,t)=>{this.reportUrl?(this.logCache.push({levelKey:e,message:`${A()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,s,i,r=5e3){this.reportUrl&&!this.reporter&&e&&(this.reporter=new H(this.reportUrl,`${t}(${this.app})`,s,i),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.logCache.unshift({levelKey:"info",message:e}),this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),r)}),{once:!0}))}_hookLogFunc(e){for(let t in V){const s=this[t];this[t]=i=>{e(t,i),s(i)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in V)V[e]<V[this.logLevel]?this[e]=u:this[e]=console[e]}get isDebugLevel(){return V[this.logLevel]<=2||this.onlineDebug}};let q;const j="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(q||(q=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),K=65536;function z(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class Y extends(n()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||Y.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Y.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=y(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void j((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var s;!t.address||t.address.endsWith(".local")?(s="Ignoring unsupported ICE candidate.",console.warn(s)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,j((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,j((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=K),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{e.debug=!0,this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>K}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=z(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=z(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((s=>{const i=[];s.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((s=>{if(this.destroyed)return;const i=[];s.result().forEach((e=>{const s={};e.names().forEach((t=>{s[t]=e.stat(t)})),s.id=e.id,s.type=e.type,s.timestamp=e.timestamp,i.push(t(s))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,s)=>{if(this.destroyed)return;t&&(s=[]);const i={},r={},n={};let a=!1;s.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(n[e.id]=e)}));const o=e=>{a=!0;let t=r[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let s=i[e.remoteCandidateId];s&&(s.ip||s.address)?(this.remoteAddress=s.ip||s.address,this.remotePort=Number(s.port)):s&&s.ipAddress?(this.remoteAddress=s.ipAddress,this.remotePort=Number(s.portNumber)):"string"==typeof e.googRemoteAddress&&(s=e.googRemoteAddress.split(":"),this.remoteAddress=s[0],this.remotePort=Number(s[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(s.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(n[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(n).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect");for(let e of this._pendingData)this.emit("data",e);this._pendingData=[]}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>K||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=a.h.from(t)),this._connected?this.emit("data",t):this._pendingData.length<10&&this._pendingData.push(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()}}Y.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Y.channelConfig={};const X=Y;class Q{constructor(e,t,s,i,r=0,n={}){this.sn=e,this.segId=t,this.data=s,this.fromPeerId=i,this.level=r,this.ext=n}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var J=s(365),Z=s.n(J);class ee extends(n()){static get defaultPacketSize(){return c}static get VERSION(){return"8"}constructor(e,t,s,i,r,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=r,this.isInitiator=i,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.signalRejectCache="",this.assignPeerId(t,s),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=c,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceiveData=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.currentLost=0,this._currentSharedPeers=[],this.notFoundPeers=new Set,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.signalName="",this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,s){this.remotePeerId=s,this.channelId=this.isInitiator?`${t}-${s}`:`${s}-${t}`,s&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=p(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:s,signalName:i}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${s} signalName ${i}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:s,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,s,i){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${i} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceiveData=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:s,seg_id:i}))))}_initPeerChannel(){const t=new X({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let s=!0;(this.connected||this.notFatalClosed)&&(s=!1);let i=t.message;t.debug&&(i=`${i} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,s,i)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.byPeerSignal?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:s}=this;if("string"==typeof t){let i;try{i=JSON.parse(t)}catch(e){return void s.error(e)}if(!i)return void s.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(i);let r,n=i.event;switch(r=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,s.debug(`datachannel receive ${r} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(i.event,i),!i.sn)return;this.config.live||(i.sn<this.startSN&&(this.startSN=i.sn),i.sn>this.endSN&&(this.endSN=i.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=p(),this.pieceMsg=i,this._prepareForBinary(i.attachments,i.seg_id,i.sn,i.size),this.emit(i.event,i);break;case e.DC_PIECE_CANCEL:s.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(i.event,i),this.sendMsgPieceAbort("transfer canceled",i.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(i.event,i);break;case e.DC_REQUEST:this._handleRequestMsg(i);break;case e.DC_PIECE_ACK:this._handlePieceAck(i.seg_id,i.size,i.miss);break;case e.DC_STATS:this._handleStats(i);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(i);break;case e.DC_METADATA:this._handleMetadata(i);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,i)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:s.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:s.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(i.event,i.fatal||!1);break;default:this.emit(i.event,i)}}else{if(!t)return void s.error("datachannel on data is undefined!");if(!this.downloading){const i=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return s.warn(i),void this.emit(e.DC_ERROR,!1,i)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,s)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const s=JSON.stringify(t);return s.length>c?(this.logger.error("string to send is too large"),!1):this.send(s,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const s=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,s)}return!1}sendMsgHave(t,s,i={}){const r=i.reverse||void 0;delete i.reverse,this.sendJson({event:r?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:s,...i})}sendPieceNotFound(t,s,i={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:s||void 0,sn:t,...i})}sendMsgStats(t,s,i={}){const r={event:e.DC_STATS,total_conns:t,shared_peers:s,...i};this.sendJson(r)}sendMsgPlaylist(t,s,i){const r=this.playlistMap.get(t);if(r&&r.seq>=i)return;const n={event:e.DC_PLAYLIST,url:t,data:s,seq:i};this.playlistMap.set(t,{data:s,seq:i}),this.sendJson(n)}sendMsgSignal(t,s,i){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:s,data:i})}sendMsgSignalReject(t,s,i,r=!1){const n=`${t}-${s}`;return this.signalRejectCache===n||(this.signalRejectCache=n,this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:s,reason:i,fatal:r}))}sendMetaData(t,s,i,r,n=!1,a=[]){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!Z().isMobile(),mobile_net:n,channel:this.channel,version:"2.17.12",sequential:s,peers:i,region:r,shared_peers:a})}sendPartialBuffer(e,t,s={}){if(!this.sendMsgPiece(e,s))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const s={...e,ext:t};return this.sendJson(s)}sendBuffer(t,s,i,r={}){const n=r.reverse||void 0;if(delete r.reverse,!i)return void this.logger.error("sendBuffer payload is undefined!");let a=i.byteLength,o=0,l=0;a%this.packetSize==0?l=a/this.packetSize:(l=Math.floor(a/this.packetSize)+1,o=a%this.packetSize);let h={event:e.DC_PIECE,attachments:l,seg_id:s,sn:t,level:r.level,size:a,reverse:n};if(delete r.level,!this.sendMsgPiece(h,r))return;const d=function(e,t,s,i){let r=[];if(i){let n;for(let i=0;i<s-1;i++)n=e.slice(i*t,(i+1)*t),r.push(n);n=e.slice(e.byteLength-i,e.byteLength),r.push(n)}else{let i;for(let n=0;n<s;n++)i=e.slice(n*t,(n+1)*t),r.push(i)}return r}(i,this.packetSize,l,o);this._sendBufferArray(d,n),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}get byPeerSignal(){return!!this.intermediator&&!this.signalName}get useBackupSignal(){return"backup"===this.signalName}requestDataById(t,s,i=!1,r={}){const n={event:e.DC_REQUEST,seg_id:t,sn:s,...r,urgent:i};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),i?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(t,s=!1,i={}){const r={event:e.DC_REQUEST,sn:t,...i,urgent:s};this.downloading?(this.logger.info(`add req ${t} in queue`),s?this.sendReqQueue.unshift(r):this.sendReqQueue.push(r)):this._realRequestData(r)}_sendBufferArray(e,t=!1){const s=t?e.reverse():e;for(let e=0;e<s.length;e++)this.send(s[e])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0,this._loadedBytes=0}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e,t){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,t&&this.incomingSignal.push(t),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:s}=t;s(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let s={event:e.DC_CLOSE,fatal:t};this.sendJson(s),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:s,reverse:i}=this.pieceMsg;let r=performance.now();0===this.timeReceiveData&&(this.timeReceiveData=r),this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let n=i?this.remainAttachments+1:s-this.remainAttachments;const a=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,n,a,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:s}=e;s(this.bufSN,this.segId,!1,t,a)}if(a){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(r-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceiveData=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:s,seq:i}=e;this.playlistMap.set(t,{data:s,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const s=this.playlistMap.get(e);return s.seq<=t||s.seq>t+2?null:s}_handleMetadata(t){const{logger:s}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,s.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const i=t.channel;if(this.channel!==i){const t=`peer channel ${i} not matched!`;return s.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){s.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:i}=this.config;if(i&&t.token!==i)return void this.emit(e.DC_ERROR,!0,`super peer token ${t.token} not matched!`)}t.region&&(this.region=t.region);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,s.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,s.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),t.shared_peers&&(this._currentSharedPeers=[...t.shared_peers]),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=p();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos),e.shared_peers&&(this._currentSharedPeers=e.shared_peers,this.notFoundPeers=new Set([...this.notFoundPeers].filter((e=>this._currentSharedPeers.some((t=>t.id===e))))))}_handleRequestMsg(t){if(this.dataExchangeTs=p(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(t,s,i){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(s/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),i>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${i}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:s})}_prepareForBinary(e,t,s,i){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=s,this.expectedSize=i}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let s=a.h.concat(this.bufArr);const i=s.byteLength;if(i===this.expectedSize){let t=s.buffer;const i=new Q(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,i,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${i}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,s=performance.now()-this.timeSendRequest;if((e||!(s<1e3))&&(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>=3&&!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`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}get currentSharedPeers(){return[...this._currentSharedPeers].filter((e=>!this.notFoundPeers.has(e.id)))}clearCurrentSharedPeers(){this._currentSharedPeers=[]}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t,s,i=!1){const r=this.datasToSend.length;if(!i&&!this.uploading&&0===r)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(s,this.bytesUploaded,0),this.bytesUploaded=0;const n={event:e.DC_PIECE_ABORT,reason:`${t}, remains ${r}`};return this.sendJson(n)}loadedBytes(){return this._loadedBytes}currentLoadSpeed(){return 0===this.timeReceiveData?0:this.loadedBytes()/(performance.now()-this.timeReceiveData)}}const te=ee,se={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",RadiantMP:"rmp",bitmovin:"bitmovin"};const ie={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class re extends(n()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===f("_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");this.segmentLoadCount=0,this.rangeTested=!1,this.trackerTried=!1,this.playerName=function(){let e;for(let t in se)if(self[t]){e=se[t];break}return e}(),this.netType=Z().getNetType()||"wifi"}resumeTracker(){this.tracker&&!this.trackerTried&&!this.tracker.connected&&this.config.p2pEnabled&&(this.tracker.resumeP2P(),this.trackerTried=!0)}onTrackerResume(e){if(e.report_url){const{logger:t}=this;t.enableReport(e.report_url);const s=(e,s)=>{t&&t.report(JSON.stringify(e,null,2),s,this.peerId,"2.17.12")};window.addEventListener("error",(e=>{s(M(e.message,e.error,e.filename),"globalJSError")}),{once:!0}),window.addEventListener("unhandledrejection",(e=>{s(M("",e.reason),"unhandledRejectionError")}),{once:!0})}}startRangeRequestTimer(){const{config:e,logger:t}=this;let s=0;const i=()=>{this.curTsUri&&function(e,t,s,i=2e3,r=!1){const n=new XMLHttpRequest;let a=e;return r&&(a=g(e,h,!0)),t=t||"bytes=0-0",new Promise(((r,o)=>{n.open("GET",a,!0),n.responseType="arraybuffer",n.timeout=i,n.onreadystatechange=e=>{if(4===n.readyState){const e=n.status;206===e?r(n.response):o(`status ${e} url ${a} range ${t}`)}},n.onerror=e=>{o("request error")},n.ontimeout=e=>{o("timeout")},n.setRequestHeader("Range",t),s&&s(n,e),n.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((r=>{e.httpRangeSupported=!1,t&&t.warn(r),s<3&&(this.rangeRequestTimer=setTimeout(i,6e4)),s++})).finally((()=>{t&&t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(i,0)}initLogger(){const{config:e}=this,t=new W(e.logLevel,e.token||location.hostname);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this;if(!e.scheduler)return;const t=e.scheduler.peersNum;return t>0&&e.maxConnsActive-t>0?e.maxConnsActive-t:void 0}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 P(t)?(s,i)=>`${e}-${t(s,i)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,s=`wss://${self.atob(function(e){let t="c2lnbmFsY2xvdWQuc3dhcm1jbG91ZC5vcmc=";switch(e){case"hk":t="c2lnbmFsLnN3YXJtY2xvdWQub3Jn";break;case"us":t="b3BlbnNpZ25hbC5zd2FybWNsb3VkLm9yZw==";break;case"cn":t="Z3ouc3dhcm1jbG91ZC5uZXQ="}return t}(t.trackerZone))}`;t.signalConfig&&(t.wsSignalerAddr=t.signalConfig);const{wsSignalerAddr:i}=t;if(i){let r;"object"==typeof i?(i.main||(i.main=s),r=i.main):"string"==typeof i&&(r=i,t.wsSignalerAddr={main:r}),r===s&&(r=void 0),r&&!t.wsSignalerAddr.backup&&(e=l().parseURL(r).netLoc.substring(2))}else t.wsSignalerAddr={main:s,byDefault:!0};return e}get commonBrowserInfo(){const e=Z().getPlatform(),{main:t,backup:s,byDefault:i}=this.config.wsSignalerAddr||{};return{signal:t,custom_signal:!i||void 0,signal2:s,device:e,netType:this.netType,player:this.playerName}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",s=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,s)};e?self.removeEventListener(t,s):self.addEventListener(t,s)}destroy(){clearTimeout(this.rangeRequestTimer),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 re.version}static isSupported(){const e=y();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,s){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${s}`);let i=4;return t<=2?i=1.5:t<=3?i=2:t<=4?i=2.5:t<=5?i=3:t<=6&&(i=3.5),i}emitEvent(e,...t){this.emit(e,...t);const s=ie[e];s&&P(this.config[s])&&this.config[s](...t)}}re.version="2.17.12",re.protocolVersion=te.VERSION;const ne=re;function ae(){if(!function(){if("object"==typeof self)return self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}())return!1;const e=self.SourceBuffer||self.WebKitSourceBuffer;return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function oe(e,t){let s;if(e&&("string"==typeof e?(s=document.querySelector(e),le(s)||(s=function(e){const t=document.getElementById(e);if(le(t))return t;if(!t)return null;const s=t.getElementsByTagName("*");for(let e=0;e<s.length;e++)if(le(s[e]))return s[e];return null}(e))):e instanceof HTMLMediaElement&&(s=e)),!s){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?s=e[0]:(t&&(s=e.find((e=>e.src===t))),s||(s=e.find((e=>e.currentTime>0))))}return s}function le(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function he(e,t,s,i=0,r=0){const n=c;let a=i,o=r||s-1;const l=Math.floor(s/n),h=s%n>0?l+1:l;if(e>=0&&(a+=(e+1)*n),t>=0&&t<h){o-=s%n+(h-t-1)*n}return{rangeStart:a,rangeEnd:o+1}}function de(e,t){return`${e}-${t}`}function ce(e,t,s,i){let r=s.split("?")[0];return r.startsWith("http")&&(r=r.split("://")[1]),i?`${r}|${i}`:`${r}`}function ue(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}let fe={wsMaxRetries:10,p2pEnabled:!0,signalCompact:!0,wifiOnly:!1,memoryCacheLimit:{pc:419430400,mobile:104857600},dcDownloadTimeout:25,logLevel:"error",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:3,trickleICE:!0,announceLocation:"eu",trackerZone:void 0,ICEPreflight:!0,useDiskCache:!0,startFromSegmentOffset:3,getStats:function(e,t,s){},getPeerId:function(e){},getPeersInfo:function(e){}};const ge={...fe,httpLoadTime:0,sharePlaylist:!1,useHttpRange:!0,hlsjsInstance:null,proxyOnly:!1,proxyFirst:!1,p2pBlackList:["vtt","webvtt","key"],live:!0,swFile:"./sw.js",swScope:"./",swAutoRegister:!0,mediaElem:void 0,httpStreamEnabled:!0,diskCacheLimit:{pc:1572864e3,mobile:1048576e3},strictSegmentId:!1,prefetchOnly:!1},pe=1e3;function me(e){const t=new Promise(((t,s)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>s(e.error)})),s=(i=pe,r="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(r)}),i))));var i,r;return Promise.race([t,s])}const ve={};async function ye(e,t,s=!0){const i=ve[e]||{};i.promise||(i.promise=new Promise((e=>i.resolve=e)),ve[e]=i,Se(e,t,i.resolve,s));const r=await i.promise;return delete i.promise,r}const Ee={};async function Se(e,t,s,i){if(!Ee[e]){const i=indexedDB.open(e);return i.onupgradeneeded=()=>{const e=i.result;t.forEach((t=>{e.createObjectStore(t)}))},void s(Ee[e]=await me(i))}if(i)try{t.forEach((t=>{Ee[e].transaction(t)})),s(Ee[e])}catch(r){console.error(`Could not open a transaction on "${e}" due to ${r.name} (${r.message}). Trying to reopen the connection...`),delete Ee[e],Se(e,t,s,i)}else s(Ee[e])}let Te;function _e(){return Te||(Te=createStore("keyval-store","keyval")),Te}function Le(e,t=_e()){return t("readonly",(t=>me(t.get(e))))}function be(e,t,s=_e()){return s("readwrite",(s=>(s.put(t,e),me(s.transaction))))}function Re(e,t=_e()){return t("readwrite",(t=>(t.delete(e),me(t.transaction))))}function Ae(e=_e()){return e("readwrite",(e=>(e.clear(),me(e.transaction))))}function Pe(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},me(e.transaction)}const we="size";class Ie extends(n()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info(`use ${this.name}`),this.engine=e,this.channel=e.channel;const s=e.browserInfo.device;this.isPC=s===Z().device.PC_WEB||s===Z().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.countErrors=0,this.isCleared=!0,this.destroyed=!1}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t<this.maxBufSize&&(this.maxBufSize=t-104857600)}return new Promise((async(e,t)=>{if(this.isPC&&this.maxBufSize<419430400||!this.isPC&&this.maxBufSize<104857600)return void t("disk storage not enough");const s=this.stores;let i;try{i=function(e,t){let s=ye(e,t);return t.map((i=>(r,n)=>s.then((a=>{try{const e=a.transaction(i,r).objectStore(i);return n(e)}catch(a){s=ye(e,t),s.then((e=>n(e.transaction(i,r).objectStore(i))))}}))))}(this.channel,s)}catch(e){return void t(e)}this._createStores(i),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return be(we,0,this.metaStore)}currBufSize(){return new Promise((async(t,s)=>{try{const i=await Le(we,this.metaStore);if(isNaN(i))return this.engine.emit(e.BM_FATAL_ERROR),void s("size is NaN");t(i)}catch(e){s(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:s}=this;if(L(t.data))return new Promise((i=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,i()})).catch((e=>{this._handleFataError(),e&&(s.warn(`putSeg ${e}`),("QuotaExceededError"===e.name||e.inner&&"QuotaExceededError"===e.inner.name)&&this.currBufSize().then((e=>{this._trimDisk(e,!0)})).catch((e=>{this.logger.error(`trimDisk ${e}`)}))),i()}))}));s.error(`putSeg ${t.segId} is not buffer`)}_handleFataError(){this.countErrors++,this.countErrors>=3&&(this.engine.emit(e.BM_FATAL_ERROR),this.countErrors=0)}_decreaseBufSize(e){this.currBufSize().then((t=>{t&&be(we,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{be(we,t+e,this.metaStore),this._trimDisk(t+e)})).catch((e=>{this.logger.warn(`increaseBufSize ${e}`)}))}clear(e=!1){if(!this.isCleared){this.logger.warn("clear segment store");try{this._clearDisk(e)}catch(e){}this.isCleared=!0}}_clearDisk(e){Ae(this.segmentsStore),e?this._initMetaStore():Ae(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}static toSegment(e){const t=new Q(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}}const De=Ie;const Ce=class extends De{constructor(e,t){super(e,t),this.loadingSN=-1,this.stores=["segments","id2Sn","metadata"]}_createStores(e){this.segmentsStore=e[0],this.id2SnStore=e[1],this.metaStore=e[2]}async hasSegOfId(e){if(!e)return Promise.resolve(!1);let t;try{t=await Le(e,this.id2SnStore)}catch(e){return Promise.resolve(!1)}return new Promise((s=>{void 0!==t?Le(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?s(!0):s(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),s(!1)})):s(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let s;try{s=await Le(e,this.id2SnStore)}catch(e){return null}return new Promise((i=>{void 0!==s?Le(s,this.segmentsStore).then((s=>{if(this.countErrors=0,s&&s.length>0){const r=s.find((t=>t.segId===e));if(!r)return void i(null);if(!L(r.data))return t.error(`getSegById ${r.sn} is not buffer`),void i(null);i(De.toSegment(r))}else i(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),i(null)})):i(null)}))}getSegIdBySN(e){return new Promise((t=>{Le(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.warn(`getSegIdBySN ${e}`),t(null)}))}))}_addSeg(e){const{segId:t,sn:s,size:i}=e;return be(t,s,this.id2SnStore),new Promise(((r,n)=>{Le(s,this.segmentsStore).then((async a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(await this._segmentToCache(e)),be(s,a,this.segmentsStore).then((()=>{this._increaseBufSize(i),r(e)})).catch((e=>{n(e)}))):r(e):be(s,[await this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(i),r(e)})).catch((e=>{n(e)}))})).catch((e=>{n(e)}))}))}async _trimDisk(t,s=!1){if(this.isCleared||this.destroyed)return;let i=this.maxBufSize;const{logger:r}=this;s&&(i=t-104857600,i<0&&(i=0)),t<i||(r.warn(`_trimDisk currentSize ${t} upBound ${i}`),function(e=_e()){return e("readonly",(e=>{if(e.getAllKeys)return me(e.getAllKeys());const t=[];return Pe(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async s=>{const n=s.sort(((e,t)=>e-t));let a=0;do{if(a++>10){r.warn("too much loops in SegmentStore");break}const s=n.shift();if(void 0===s){r.warn("lastSN not found");continue}if(s>=this.loadingSN){r.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const i=n[0],o=await Le(s,this.segmentsStore);if(!o){r.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),Re(s,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((t=>{Re(t.segId,this.id2SnStore),r.info(`pop seg ${t.segId} size ${t.data.byteLength}`),this.emit(e.BM_LOST,{sn:s,segId:t.segId,next:i,level:t.level})})),t-=l,r.info(`pop sn ${s} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=i)})))}async _segmentToCache(e){const{ext:t={}}=e;let s=t.hash;s||(s=await k(e.data));const i={data:e.data,level:e.level,segId:e.segId,sn:e.sn,fromPeerId:e.fromPeerId,ext:{}};return s&&(i.ext.hash=s),i}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}Ae(this.id2SnStore).catch((e=>{}))}};class ke extends(n()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const s=e.browserInfo.device;if(this.maxBufSize=s===Z().device.PC_WEB||s===Z().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,this.isLive=t.live,this.isLive)this.maxBufSize=47185920;else{if(0===this.maxBufSize)throw new Error("cannot use SegmentCache");const e=function(){const{memory:e}=performance;return e?e.jsHeapSizeLimit-e.usedJSHeapSize:-1}();e>=0&&e<this.maxBufSize&&(this.maxBufSize=e-31457280)}this._segPool=new Map,this._currBufSize=0,this.overflowed=!1,this.isCleared=!0,this.destroyed=!1}get currBufSize(){return this._currBufSize}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}async putSeg(e){this.destroyed||(this.isCleared=!1,this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),L(e.data)?this._addSeg(e):this.logger.error(`putSeg ${e.segId} is not buffer`))}clear(){this.isCleared||(this.logger.warn("clear segment cache"),this._segPool.clear(),this._currBufSize=0,this.isCleared=!0,this.overflowed=!1)}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Me=ke;const xe=class extends Me{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,s)=>{const i=this.id2Sn.get(e);this._segPool.has(i)?t(this._segPool.get(i).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((s,i)=>{if(!this._segPool.has(t))return void s(null);const r=this._segPool.get(t).find((t=>t.segId===e));s(r||null)}))}getSegIdBySN(e){return new Promise(((t,s)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}async _addSeg(t){const{logger:s}=this,{segId:i,sn:r,size:n,ext:a={}}=t;if(this.id2Sn.set(i,r),this._segPool.has(r)){this._segPool.get(r).push(t)}else this._segPool.set(r,[t]);this._currBufSize+=parseInt(n);const o=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSize<this.maxBufSize||o<=5)return;let l=Array.from(this._segPool.keys());this.isLive||(l=l.sort(((e,t)=>e-t)));let h=0;do{if(h++>10){s.error("too much loops in SegmentCache");break}const t=l.shift();if(void 0===t){s.error("lastSN not found");continue}const i=l[0],r=this._segPool.get(t);if(!r){s.error("lastSeg not found");continue}let n=0;r.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(t),r.forEach((s=>{this.id2Sn.delete(s.segId),this.emit(e.BM_LOST,{sn:t,segId:s.segId,next:i,level:s.level})})),s.info(`pop sn ${t} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){super.clear(),this.id2Sn.clear()}};function Oe(e,t){for(const s in t)Object.defineProperty(e,s,{value:t[s],enumerable:!0,configurable:!0});return e}const Fe=function(e,t,s){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");s||(s={}),"object"==typeof t&&(s=t,t=void 0),null!=t&&(s.code=t);try{return Oe(e,s)}catch(t){s.message=e.message,s.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),Oe(new i,s)}};class Ne{constructor(){this.p2p=0,this.share=0,this.http=0}recordP2p(e){this.p2p+=e}recordShare(e){this.share+=e}recordHttp(e){this.http+=e}resetTraffic(){this.p2p=0,this.share=0,this.http=0}get healthRatio(){if(0===this.http)return 1e3;let e=Math.round((this.p2p+this.share)/this.http*100);return e<=0&&(e=1),e}}const $e="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class Be{constructor(e=new Uint8Array(16)){this.buf=ArrayBuffer.isView(e)?e:new Uint8Array(e),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(e,t,s=this.length){for(;this.pos<s;){const s=this.readVarint(),i=s>>3,r=this.pos;this.type=7&s,e(i,t,this),this.pos===r&&this.skip(s)}return t}readDouble(){const e=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,e}readVarint(e){const t=this.buf;let s,i;return i=t[this.pos++],s=127&i,i<128?s:(i=t[this.pos++],s|=(127&i)<<7,i<128?s:(i=t[this.pos++],s|=(127&i)<<14,i<128?s:(i=t[this.pos++],s|=(127&i)<<21,i<128?s:(i=t[this.pos],s|=(15&i)<<28,function(e,t,s){const i=s.buf;let r,n;if(n=i[s.pos++],r=(112&n)>>4,n<128)return Ue(e,r,t);if(n=i[s.pos++],r|=(127&n)<<3,n<128)return Ue(e,r,t);if(n=i[s.pos++],r|=(127&n)<<10,n<128)return Ue(e,r,t);if(n=i[s.pos++],r|=(127&n)<<17,n<128)return Ue(e,r,t);if(n=i[s.pos++],r|=(127&n)<<24,n<128)return Ue(e,r,t);if(n=i[s.pos++],r|=(1&n)<<31,n<128)return Ue(e,r,t);throw new Error("Expected varint not more than 10 bytes")}(s,e,this)))))}readBoolean(){return Boolean(this.readVarint())}readString(){const e=this.readVarint()+this.pos,t=this.pos;return this.pos=e,e-t>=12&&$e?$e.decode(this.buf.subarray(t,e)):function(e,t,s){let i="",r=t;for(;r<s;){const t=e[r];let n,a,o,l=null,h=t>239?4:t>223?3:t>191?2:1;if(r+h>s)break;1===h?t<128&&(l=t):2===h?(n=e[r+1],128==(192&n)&&(l=(31&t)<<6|63&n,l<=127&&(l=null))):3===h?(n=e[r+1],a=e[r+2],128==(192&n)&&128==(192&a)&&(l=(15&t)<<12|(63&n)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===h&&(n=e[r+1],a=e[r+2],o=e[r+3],128==(192&n)&&128==(192&a)&&128==(192&o)&&(l=(15&t)<<18|(63&n)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,h=1):l>65535&&(l-=65536,i+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),i+=String.fromCharCode(l),r+=h}return i}(this.buf,t,e)}skip(e){const t=7&e;if(0===t)for(;this.buf[this.pos++]>127;);else if(2===t)this.pos=this.readVarint()+this.pos;else if(5===t)this.pos+=4;else{if(1!==t)throw new Error(`Unimplemented type: ${t}`);this.pos+=8}}writeTag(e,t){this.writeVarint(e<<3|t)}realloc(e){let t=this.length||16;for(;t<this.pos+e;)t*=2;if(t!==this.length){const e=new Uint8Array(t);e.set(this.buf),this.buf=e,this.dataView=new DataView(e.buffer),this.length=t}}finish(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)}writeVarint(e){(e=+e||0)>268435455||e<0?function(e,t){let s,i;e>=0?(s=e%4294967296|0,i=e/4294967296|0):(s=~(-e%4294967296),i=~(-e/4294967296),4294967295^s?s=s+1|0:(s=0,i=i+1|0));if(e>=0x10000000000000000||e<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");t.realloc(10),function(e,t,s){s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos++]=127&e|128,e>>>=7,s.buf[s.pos]=127&e}(s,0,t),function(e,t){const s=(7&e)<<4;if(t.buf[t.pos++]|=s|((e>>>=3)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;if(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),!e)return;t.buf[t.pos++]=127&e}(i,t)}(e,this):(this.realloc(4),this.buf[this.pos++]=127&e|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=e>>>7&127))))}writeBoolean(e){this.writeVarint(+e)}writeString(e){e=String(e),this.realloc(4*e.length),this.pos++;const t=this.pos;this.pos=function(e,t,s){for(let i,r,n=0;n<t.length;n++){if(i=t.charCodeAt(n),i>55295&&i<57344){if(!r){i>56319||n+1===t.length?(e[s++]=239,e[s++]=191,e[s++]=189):r=i;continue}if(i<56320){e[s++]=239,e[s++]=191,e[s++]=189,r=i;continue}i=r-55296<<10|i-56320|65536,r=null}else r&&(e[s++]=239,e[s++]=191,e[s++]=189,r=null);i<128?e[s++]=i:(i<2048?e[s++]=i>>6|192:(i<65536?e[s++]=i>>12|224:(e[s++]=i>>18|240,e[s++]=i>>12&63|128),e[s++]=i>>6&63|128),e[s++]=63&i|128)}return s}(this.buf,e,this.pos);const s=this.pos-t;s>=128&&function(e,t,s){const i=t<=16383?1:t<=2097151?2:t<=268435455?3:Math.floor(Math.log(t)/(7*Math.LN2));s.realloc(i);for(let t=s.pos-1;t>=e;t--)s.buf[t+i]=s.buf[t]}(t,s,this),this.pos=t-1,this.writeVarint(s),this.pos+=s}writeDouble(e){this.realloc(8),this.dataView.setFloat64(this.pos,e,!0),this.pos+=8}writeVarintField(e,t){this.writeTag(e,0),this.writeVarint(t)}writeStringField(e,t){this.writeTag(e,2),this.writeString(t)}writeDoubleField(e,t){this.writeTag(e,1),this.writeDouble(t)}writeBooleanField(e,t){this.writeVarintField(e,+t)}}function Ue(e,t,s){return s?4294967296*t+(e>>>0):4294967296*(t>>>0)+(e>>>0)}function Ge(e,t){return e.readFields(He,{},t)}function He(e,t,s){1===e?t.id=s.readString():2===e?t.ip=s.readString():3===e?t.country=s.readString():4===e?t.isp=s.readString():6===e?t.conns=s.readVarint(!0):7===e?t.fail_rate=s.readDouble():8===e?t.mobile=s.readBoolean():9===e?t.source=s.readString():10===e?t.score=s.readDouble():11===e?t.lon=s.readDouble():12===e?t.lat=s.readDouble():13===e?t.platform=s.readString():14===e&&(t.super=s.readBoolean())}function Ve(e,t){e.channel&&t.writeStringField(1,e.channel),e.device&&t.writeStringField(2,e.device),e.live&&t.writeBooleanField(3,e.live),e.tag&&t.writeStringField(4,e.tag),e.ts&&t.writeVarintField(5,e.ts),e.type&&t.writeStringField(6,e.type),e.version&&t.writeStringField(7,e.version),e.netType&&t.writeStringField(8,e.netType),e.app&&t.writeStringField(9,e.app),e.nat&&t.writeStringField(12,e.nat),e.token&&t.writeStringField(14,e.token),e.k&&t.writeStringField(15,e.k),e.abr&&t.writeBooleanField(16,e.abr),e.pos&&t.writeVarintField(25,e.pos),e.signal&&t.writeStringField(26,e.signal),e.signal2&&t.writeStringField(27,e.signal2),e.custom_signal&&t.writeBooleanField(28,e.custom_signal)}function We(e,t,s){1===e?t.id=s.readString():2===e?t.ip=s.readString():3===e?t.country=s.readString():4===e?t.asn=s.readString():8===e?t.total=s.readVarint(!0):9===e?t.score=s.readString():11===e?t.report_interval=s.readVarint(!0):12===e?t.peers.push(Ge(s,s.readVarint()+s.pos)):13===e?t.info=s.readString():14===e?t.warn=s.readString():15===e?t.rejected=s.readBoolean():16===e?t.min_conns=s.readVarint(!0):17===e?t.wifi_only=s.readBoolean():18===e?t.signal=s.readString():19===e?t.signal2=s.readString():20===e?t.stun.push(s.readString()):21===e?t.log_url=s.readString():22===e?t.report_url=s.readString():23===e?t.debug=s.readBoolean():24===e?t.fuse_rate=s.readVarint(!0):25===e?t.token=s.readString():26===e?t.token2=s.readString():27===e?t.slogan=s.readBoolean():30===e&&(t.overload=s.readBoolean())}function qe(e,t){if(e.exclusions)for(const s of e.exclusions)t.writeStringField(1,s);e.level&&t.writeStringField(2,e.level),e.num_want&&t.writeVarintField(3,e.num_want),e.urgent&&t.writeBooleanField(6,e.urgent),e.ratio&&t.writeVarintField(7,e.ratio)}function je(e,t,s){1===e?t.peers.push(Ge(s,s.readVarint()+s.pos)):2===e?t.total=s.readVarint(!0):3===e?t.score=s.readString():4===e&&(t.pos=s.readString())}function Ke(e,t){e.p2p&&t.writeVarintField(1,e.p2p),e.http&&t.writeVarintField(2,e.http),e.share&&t.writeVarintField(3,e.share),e.conns&&t.writeVarintField(4,e.conns),e.totalConns&&t.writeVarintField(5,e.totalConns),e.failConns&&t.writeVarintField(6,e.failConns),e.rebuffers&&t.writeVarintField(7,e.rebuffers),e.requests&&t.writeVarintField(8,e.requests),e.pos&&t.writeVarintField(10,e.pos),e.level&&t.writeStringField(11,e.level),e.off&&t.writeBooleanField(12,e.off)}function ze(e,t,s){1===e?t.code=s.readVarint(!0):2===e&&(t.msg=s.readString())}function Ye(e,t,s){1===e?t.ret=s.readVarint(!0):2===e?(t.channel_response=function(e,t){return e.readFields(We,{peers:[],stun:[]},t)}(s,s.readVarint()+s.pos),t.data="channel_response"):3===e?(t.peers_response=function(e,t){return e.readFields(je,{peers:[]},t)}(s,s.readVarint()+s.pos),t.data="peers_response"):4===e&&(t.err_data=function(e,t){return e.readFields(ze,{code:0},t)}(s,s.readVarint()+s.pos),t.data="err_data")}const Xe=class{constructor(e){this.currentIndex=0,this.domains=[...e]}getCurrentDomain(){return this.domains[this.currentIndex]}switchToNextDomain(){return this.currentIndex=(this.currentIndex+1)%this.domains.length,0!==this.currentIndex}getAllDomains(){return[...this.domains]}},Qe="TRACKER_EXPT",Je={cn:["Z3o"+"uY2R"+"uYnll"+"LmNv"+"bQ=="],hk:["aGsubWVzaGlmeS5jbG91ZA==","aGsuc3dhcm1jbG91ZC5vcmc=","aGsud2ViMy1sYWIuY29tOjIwOTY=","aGsuZ29vb2dvbC5jb20=","aGsucDJwZW5naW5lLm5ldA=="],eu:["ZXUubWVzaGlmeS5jbG91ZA==","ZXUuc3dhcm1jbG91ZC5vcmc=","ZXUud2ViMy1sYWIuY29tOjg0NDM=","ZXUuZ29vb2dvbC5jb20=","ZXUucDJwZW5naW5lLm5ldA=="],us:["dXMubWVzaGlmeS5jbG91ZA==","dXMuc3dhcm1jbG91ZC5vcmc=","dXMud2ViMy1sYWIuY29tOjg0NDM=","dXMuZ29vb2dvbC5jb20=","dXMucDJwZW5naW5lLm5ldA=="]},Ze=Symbol("httpDownloaded"),et=Symbol("p2pDownloaded"),tt=Symbol("p2pUploaded");class st extends(n()){constructor(e,t,s,i,r){super(),this.config=e.config;let n=this.config.announceLocation;this.config.trackerZone&&(n=this.config.trackerZone),this.engine=e,this.key=t||void 0;let a=(Je[n]||Je.eu).map((e=>`https://${self.atob(e)}/v1`));i&&(a=x(Array.isArray(i)?[...i]:[i])),this.domainMgr=new Xe(a),this.channelId=self.btoa(s),this.timestamp=p(),this.health=new Ne,this.native=!(!r.bundle||!window.electron&&!navigator.userAgent.toLowerCase().includes("electron")),this.announceInfo={...r,channel:this.channelId,ts:this.timestamp,version:"2.17.12",k:at(this.key)},this.reportFails=0,this.statsRequesting=!1,this.statsLimited=!1,this.reportInterval=30,this.bigValueReported=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[Ze]=0,this[et]=0,this[tt]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0}get announceURL(){return`${this.domainMgr.getCurrentDomain()}/channel`}get getPeersURL(){return`${this.domainMgr.getCurrentDomain()}/channel/${this.channelId}/node/${this.peerId}/peers`}get statsURL(){return`${this.domainMgr.getCurrentDomain()}/channel/${this.channelId}/node/${this.peerId}/stats`}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,s)=>{ot(this.announceURL,this._requestHeader,this.announceInfo,Ve,((e,t)=>{if(!e){const e=t>=500&&t<600;s(Fe(new Error(`server response code is ${t}`),Qe,{retry:e}))}}),(e=>{if(!this.engine||!e)return;const i=e.data;if(i){if(i.slogan&&console.log(`%cLet the browsers become your unlimitedly scalable CDN!\n%cGet Free Trial \u{1f449} ${self.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldA==")} ${self.atob("aHR0cHM6Ly9zd2FybS1jbG91ZC5naXRodWIuaW8vaG9tZQ==")}`,"color: dodgerblue; padding:20px 0; font-size: xx-large","font-size: medium; padding-bottom:15px"),i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),-1===e.ret){const{code:t,msg:i}=e.data;s(Fe(new Error(i),Qe,{retry:t>=5e3}))}if((!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval){if(this.peerId=this.id=i.id,i.report_interval<20&&(i.report_interval=20),this.reportInterval=i.report_interval,this.btStats(),!this.announceInfo.asn&&i.asn){const{country:e,asn:t}=i;this.engine.emitEvent("geographicInfo",{country:e,asn:t}),this.announceInfo={...this.announceInfo,country:e,asn:t}}this.engine.emitEvent("serverConnected",!0),t(i)}else this.engine&&(this.engine.p2pEnabled=!1)}}),(t=>{let i=!1;e.error(`announce error ${t}`);const r=t.code||Qe,n=!t.code||t.retry;this.domainMgr.switchToNextDomain()&&(i=!0),s(Fe(t,r,{retry:n,immediate:i}))}))}))}btStats(){clearInterval(this.heartbeater),this.heartbeater=setInterval((()=>{this.postStats()}),1e3*this.reportInterval)}postStatsWithBeacon(){if(this.offline)return;this.engine.emitEvent("serverConnected",!1),this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),this.peerId&&navigator.sendBeacon&&navigator.sendBeacon(this.statsURL,lt(e,Ke))}postStats(t=!1){const{logger:s}=this.engine;if(this.statsRequesting)return!1;if(t){if(this.statsLimited)return!1;this.btStats()}return this.statsLimited=t,this.statsRequesting=!0,ot(this.statsURL,{},this._makeStatsBody(),Ke,(()=>{this.statsRequesting=!1,this.reportFails=0}),(t=>{if(t||(t={ret:0,data:{}}),-1===t.ret)clearInterval(this.heartbeater),s.error(`${t.data.msg} code ${t.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:s=0,failConns:i=0,rebuffers:r=0,requests:n=0}=this.lastStats||{};this[Ze]>=e&&(this[Ze]-=e),this[et]>=t&&(this[et]-=t),this[tt]>=s&&(this[tt]-=s),this.failConns>=i&&(this.failConns-=i),this.errsBufStalled>=r&&(this.errsBufStalled-=r),this.mediaRequests>=n&&(this.mediaRequests-=n)}this.bigValueReported&&(this[et]=0,this.bigValueReported=!1)}),(t=>{s.error(`stats error ${t}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&(clearInterval(this.heartbeater),this.engine.emit(e.RESTART_P2P))})),!0}btGetPeers(e,t=!1){const{logger:s}=this.engine;let i={exclusions:e,ratio:this.health.healthRatio,urgent:t||void 0},r={};return this.engine.getExtraForPeersRequest&&(r=this.engine.getExtraForPeersRequest()),i=Object.assign({},i,r),new Promise(((e,t)=>{this.reportFails>=3?t(new Error("reportFails >= 3")):ot(this.getPeersURL,this._requestHeader,i,qe,null,(s=>{-1===s.ret?t(s.data.msg):e(s.data)}),(e=>{s.error(`getPeers error ${e}`),t(e)}),(()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.engine.emitEvent("bufferStalled"),this.errsBufStalled++}increMediaRequests(){this.mediaRequests++,this.engine.emit(e.MEDIA_REBUFFER,this.errsBufStalled>=2)}reportFlow(e){const t=Math.round(e/1024);this.engine.emitEvent("httpDownloaded",t),this[Ze]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const s=Math.round(e/1024);this[et]+=s,this.totalP2PDownloaded+=s,this.health.recordP2p(s),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",s,this.speed),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.engine.emitEvent("p2pUploaded",t),this.totalP2PUploaded+=t,this.health.recordShare(t),this[tt]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){const{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:s}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:s,p2pDownloadSpeed:this.speed});const{getStats:i}=this.config;P(i)&&i(t,s,e,this.speed)}_makeStatsBody(){let e={totalConns:this.engine.tracker.totalConns+1,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,http:Math.round(this[Ze])||0,p2p:Math.round(this[et])||0,share:Math.round(this[tt])||0},t={};this.engine.getExtraForStats&&(t=this.engine.getExtraForStats()),e=Object.assign({},e,t),this.lastStats=JSON.parse(JSON.stringify(e)),Object.keys(e).forEach((t=>{0===e[t]&&delete e[t]}));const{logger:s}=this.engine;return s.isDebugLevel&&s.info(`report ${JSON.stringify(e)}`),this[et]>1e6&&(this.bigValueReported=!0),e}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":at(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const it=st;function rt(e,t){const s=nt();return(rt=function(e,t){return s[e-=0]})(e,t)}function nt(){const e=["CsLPpZ8932212".split("").reverse().join(""),"htgnel".split("").reverse().join(""),"UZpUzY5895021".split("").reverse().join(""),"yJZuxA9452121".split("").reverse().join(""),"tAedoCrahc".split("").reverse().join(""),"btoa","q#<K@C".split("").reverse().join(""),"1164HyWkyu","4154136SJSwNe","IITNvu6344771".split("").reverse().join(""),"edoCrahCmorf".split("").reverse().join(""),"554Biqadw","oShtCc7412072".split("").reverse().join("")];return(nt=function(){return e})()}function at(e){if(!e)return;const t=rt(-822- -830,-826);let s="".split("").reverse().join("");const i=t.length;for(let r=0;r<e.length;r++){const n=e.charCodeAt(r)^t.charCodeAt(r%i);s+=String.fromCharCode(n)}return self.btoa(s)}function ot(e,t,s,i,r,n,a,o){let l;t={...t},s&&(l=lt(s,i)),fetch(e,{method:"POST",headers:t,body:l}).then((e=>{e.ok?(r&&r(!0),e.arrayBuffer().then((e=>{let t;try{t=new Be(e).readFields(Ye,{ret:0},s);const i=t[t.data];delete t[t.data],t.data=i}catch(s){try{const s=new TextDecoder("utf-8").decode(e);t=JSON.parse(s)}catch(e){t=null}}var s;n&&n(t)}))):r&&r(!1,e.status)})).catch((e=>{a&&a(e)})).finally((()=>{o&&o()}))}function lt(e,t){const s=new Be;t(e,s);return s.finish()}!function(e,t){const s=e();function i(e,t,s,i,r){return rt(e-92,r)}function r(e,t,s,i,r){return rt(r-930,s)}for(;;)try{if(377468===parseInt(r(0,0,944,0,939))/1*(parseInt(r(0,0,936,0,930))/2)+parseInt(r(0,0,929,0,935))/3+parseInt(r(0,0,939,0,941))/4+-parseInt((n=-995,a=-995,rt(n- -999,a)))/5+parseInt(i(94,0,0,0,91))/6+-parseInt(i(93,0,0,0,92))/7+-parseInt(i(102,0,0,0,107))/8)break;s.push(s.shift())}catch(e){s.push(s.shift())}var n,a}(nt);class ht extends(n()){constructor(e,t){super(),this.logger=e,t.startsWith("wss")?this.addr=t.replace("wss","https"):t.startsWith("ws")&&(this.addr=t.replace("ws","http")),this.connected=!1,this.retryCount=0,this.closed=!1,this.msgQueue=[],this.posting=!1,this.pollingTs=0}start(){this.closed=!1,this._hello((()=>{this._longPolling()}))}_hello(e){fetch(this.addr+"&hello",{method:"POST"}).then((e=>{if(!e.ok)throw new Error("hello response was not ok");return e.json()})).then((t=>{this.connected=!0,e(),this.onopen&&this.onopen(t.ver)})).catch((e=>{this.closed=!0,this.onerror&&this.onerror(e)}))}send(e){this.msgQueue.push(e),this.posting||this._realSend([...this.msgQueue])}_realSend(e){0!==e.length&&(this.posting=!0,this.msgQueue=[],fetch(this.addr,{method:"POST",body:JSON.stringify(e)}).then((()=>{this.posting=!1,this.msgQueue.length>0&&this._realSend([...this.msgQueue])})).catch((e=>{this.logger.error(e),this.posting=!1})))}close(){this.connected&&(this.closed=!0,this.connected=!1,this.abortController&&(this.abortController.abort(),this.abortController=null),this.onclose&&this.onclose())}destroy(){this.close(),this.removeAllListeners()}_longPolling(){if(this.closed)return;this.pollingTs=p(),this.abortController=new AbortController;const e=this.abortController.signal;fetch(this.addr,{signal:e}).then((e=>{if(!e.ok)throw new Error("polling response was not ok");return e.text()})).then((async e=>{e&&this.onmessage&&this.onmessage(JSON.parse(e)),this.retryCount=0;const t=p()-this.pollingTs;JSON.stringify(e)===JSON.stringify(this.lastData)&&t<10&&(this.logger.warn(`wait ${10-t}s for next polling`),await v(1e3*(10-t))),this.lastData=e,this._longPolling()})).catch((e=>{this.connected&&(this.retryCount<=3?(this.retryCount++,this._longPolling()):(this.connected=!1,this.onerror&&this.onerror(e)))}))}}const dt=class{constructor(e,t,s,i="main"){this.logger=e,this.config=t,this.wsAddr=s,this.serverVersion=0,this.pingInterval=95e3,this.name=i,this.normalClosed=!1,this.connecting=!0,this.lastSendTs=performance.now(),this.pollingClient=new ht(e,s);try{this._ws=this._init()}catch(t){e.error(t),this._startPolling()}}get batchSupported(){return this.serverVersion>=50}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:m(15e3,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20,connectionTimeout:7e3};let t=new U(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.normalClosed=!1,this.connecting=!1,this.pollingClient.connected?this.pollingClient.close():this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{this.lastSendTs=performance.now();let s=JSON.stringify(e);t.push(s)},t.addEventListener("message",(e=>{let t=e.data;const s=JSON.parse(t),i=s.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${s.reason}`),void this.close()):void("signals"!==i?this.onmessage&&this.onmessage(s,this.name):this._onSignalBatch(s.data));this.serverVersion=s.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{const{code:t,reason:s}=e;this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${t} ${s}`),t>=5e3||t<4e3?(this.onclose&&this.onclose(),this._stopPing()):this.close(),this.connecting=!1})),t.addEventListener("error",(e=>{this._stopPing(),this.onerror&&this.onerror(e),this._startPolling()})),t}_startPolling(){this.normalClosed||this.pollingClient.connected||(this.logger.info(`${this.name} start polling`),this.pollingClient.start(),this._setupPolling(this.pollingClient))}sendDebug(e,t,s){this._send({action:"debug",details:t,ping:s||void 0,to:e})}sendSignal(e,t){const s={action:"signal",to:e,data:t};return this._send(s),this.name}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let s of t)this.sendSignal(e,s);return this.name}sendReject(e,t,s){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const i={action:"reject",to:e,reason:t,fatal:s};this._send(i)}_send(e){this.pollingClient.connected?this.pollingClient.send(e):this._ws&&this._ws.send(e)}_startPing(e){this.connected&&(this.pingTimer=setTimeout((()=>{const e=95e3-(performance.now()-this.lastSendTs);if(e>=0)return this._startPing(e);const t={action:"ping"};this._ws&&this._ws.push(JSON.stringify(t)),this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3),this._startPing(this.pingInterval)}),e))}_stopPing(){clearTimeout(this.pingTimer),clearTimeout(this.pongTimer)}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3)})(),this.pollingClient.close(),this.normalClosed=!0}reconnect(){return!(!this._ws||this.connecting)&&(this.connecting=!0,this.normalClosed=!1,this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect(),!0)}destroy(){this.close(),this._ws=null,this.pollingClient.destroy()}get connected(){return!!this.pollingClient.connected||this._connected}get _connected(){return!!this._ws&&this._ws.readyState===U.OPEN}_setupPolling(e){e.onopen=e=>{e&&(this.serverVersion=e),this.logger.info(`${this.name} polling opened`),this.connecting=!1,this.onopen&&this.onopen()},e.onerror=e=>{this._connected||this.onerror&&this.onerror(e)},e.onclose=()=>{this._connected||this.onclose&&this.onclose()},e.onmessage=e=>{if(this.onmessage)for(let t of e)"signals"===t.action?this._onSignalBatch(t.data):this.onmessage(t,this.name)}}_onSignalBatch(e){if(this.onmessage)for(let t of e)t.action||(t.action="signal"),this.onmessage(t,this.name)}},ct=class{constructor(e,t,s,i){this.logger=e,this.config=t,this.mainAddr=s,this.backupAddr=i,this.mainWS=this._init(s),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(i,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let s=new dt(this.logger,this.config,e,t);return s.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},s.onmessage=e=>{this.onmessage&&this.onmessage(e,s.name)},s.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},s.onerror=e=>{this.onerror&&this.onerror(e)},s}sendSignalBatch(e,t,s){if(s){const i=this._getWSByName(s);if(i)return i.sendSignalBatch(e,t)}return this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected?this.backupWS.sendSignalBatch(e,t):null}sendSignal(e,t,s){return this.sendSignalBatch(e,[t],s)}sendReject(e,t,s,i){if(i){const r=this._getWSByName(i);if(r)return void r.sendReject(e,t,s)}this.mainConnected?this.mainWS.sendReject(e,t,s):this.backupConnected?this.backupWS.sendReject(e,t,s):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,s){this.mainConnected&&this.mainWS.sendDebug(e,t,s)}close(){this.mainWS&&this.mainWS.close(),this.backupWS?this.backupWS.close():this.backupTimer&&clearTimeout(this.backupTimer),this.normalClosed=!0}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(e){let t=!1;return this.mainWS&&"backup"!==e&&this.mainWS.reconnect()&&(t=!0),this.backupWS&&"main"!==e&&this.backupWS.reconnect()&&(t=!0),t}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}get connecting(){let e=!1;return this.mainWS&&this.mainWS.connecting&&(e=!0),this.backupWS&&this.backupWS.connecting&&(e=!0),e}};const ut=function(e,t,s=40){var i=null,r=!1,n=s;return function(s=!1){if(s)return clearTimeout(i),void(r=!1);r||(r=!0,i=setTimeout((function(){e.call(t,n),r=!1,i=null}),1e3*n),n*=1.1)}};class ft{constructor(e,t,s=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=s,this.pool=[],t.ICEPreflight&&this.reset(),this.trickle=!1}reset(){this.destroy();for(let e=0;e<this.poolSize;e++)this.pool.push(this._createPeer())}_createPeer(){return new te(this.engine,void 0,void 0,!0,this.config,{trickle:this.trickle})}get available(){return 0!==this.pool.length&&this.pool[0].signalMsgs.length>0}getPeer(){if(0===this.pool.length)return this._createPeer();const e=this.pool.shift();return this.pool.length<5&&this.pool.push(this._createPeer()),e}destroy(){for(let e of this.pool)e.destroy(!0);this.pool=[]}}const gt=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,s=0,i="";for(const r of e){if("="===r)break;const e=this.CHARSET.indexOf(r);for(t=t<<this.BITS_PER_BASE64_CHAR|e,s+=this.BITS_PER_BASE64_CHAR;s>=this.BITS_PER_BYTE;){s-=this.BITS_PER_BYTE;i+=(t>>s&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let r="";for(let e=0;e<i.length;e++)r+=i[e],e%2==1&&e!==i.length-1&&(r+=":");return r}},pt="typ host",mt="generation 0",vt="network-cost",yt="rport",Et="0.0.0.0",St={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},Tt={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},_t={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},Lt={P:`${pt} ${mt} ${vt} 999`,W:`${yt} 0 ${mt} ${vt} 999`,H:pt,S:"typ srflx",R:yt,A:"raddr",V:Et,F:"ufrag",G:`${yt} 0 ${mt}`,N:vt,E:"network-id",C:"tcptype active",Q:`${mt}`,U:"udp",T:"tcp"},bt={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Rt={4:"IP4",6:"IP6"},At={0:Et},Pt=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in Lt&&(e=Lt[e]),e))).join(" "));function wt(e,t){let s=e.split("~"),i=[];s=s.map((e=>{let t=e.slice(0,1),s=e.slice(1);if(t in St&&(t=St[t]),"a="===t){let e=s.slice(0,1);const t=s.slice(1);e in Tt&&(e=Tt[e],s=e+t)}return t+s})),i.push("v=0"),i.push("s=-"),i.push("t=0 0"),i.push("a=msid-semantic: WMS");let r=0;s.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),s=[];s.push("-");const r=t.shift();if(r&&s.push(r),0===t.length)s.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&s.push(e),0===t.length)s.push("IN IP4 127.0.0.1");else{s.push("IN");const e=t.shift();e&&s.push(e);const i=t.shift();i&&s.push(i)}}i.splice(1,0,`o=${s.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(It,(e=>bt[e]))}(e),i.push(e),i.push("a=setup:"+(t?"actpass":"active")),i.push(`a=mid:${r}`),void r++;if(e.startsWith("a=candidate:"))return e=Pt(e),void i.push(e);if(e.startsWith("a=fingerprint:")){let[t,s]=e.slice(14).split(" ");return t in _t&&(t=_t[t]),s=gt.decode(s),void i.push(`a=fingerprint:${t} ${s}`)}if(e.startsWith("c=")){let[t,s]=e.slice(2).split(" ");return t in Rt&&(t=Rt[t]),s in At&&(s=At[s]),void i.push(`c=IN ${t} ${s}`)}"I"!==e?"Z"!==e?"B"!==e?i.push(e):i.push("a=sendrecv"):i.push("a=ice-options:ice2,trickle"):i.push("a=ice-options:trickle")}}));const n=i.length-1;return i.splice(n,0,`a=group:BUNDLE ${Array.from(Array(r).keys()).join(" ")}`),i.join("\r\n")}const It=new RegExp(Object.keys(bt).join("|"),"g");class Dt extends(n()){constructor(e,t,s,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=s,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set,this.isMobile=e.isMobileNet,this.peerPool=new ft(e,i,10),this.signalerWs=null,this.fetcher=t,this.peers=[],this.minConns=8,this.stuns=[],this.requestMorePeers=ut(this._requestMorePeers,this,m(35,45)),this.maxConns=this.isMobile?15:20,this.maxConnsActive=this.isMobile?12:13,this.fuseRate=-1,this.overloaded=!1,this.signalRejectCache="",this.maxPeersBySignalServer=12,this._startCheckConnsTimer()}get totalConns(){return this.scheduler.peersNum}get isReachActiveLimit(){return this.DCMap.size>=this.maxConnsActive}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:s,fetcher:i}=this,{wsSignalerAddr:r,wifiOnly:n}=s;i.btAnnounce().then((e=>{const{scheduler:s}=this;if(!s)return;t.peerId=this.peerId=e.id,e.min_conns&&(this.minConns=e.min_conns);const i=e.peers||[];s.notifyPeersLoaded(i.length),(e.wifi_only||n)&&this.isMobile&&(s.downloadOnly=!0,this.logger.info("downloadOnly mode"));const a=r.main;let o=r.backup;if(e.signal&&!e.signal2&&(o=void 0),this.signalerWs=this._initSignalerWs(e.signal||a,e.signal2||o,e.token,e.token2),0===i.length?this.requestMorePeers():this.peers=i,t.emitEvent("peerId",this.peerId),e.stun&&e.stun.length>0&&(this.stuns=e.stun),e.debug&&(this.logger.enableDebug(),e.log_url)){this.logUploader=new H(e.log_url,this.fetcher.key||location.hostname,this.peerId,"2.17.12"),this.logger.setUploader(this.logUploader);const{domainMgr:t}=this.fetcher,s=t.getAllDomains();s.length>1&&(this.logger.warn(`all domain: ${s}`),this.logger.warn(`current domain: ${t.getCurrentDomain()}`))}t.onTrackerResume&&t.onTrackerResume(e),e.fuse_rate&&(this.maxConnsActive=this.fuseRate=e.fuse_rate,this.maxConns=this.maxConnsActive+(this.isMobile?3:7),this.maxPeersBySignalServer=7),e.overload&&(this.overloaded=!0,this.maxPeersBySignalServer=3,this.logger.warn("server overloaded, degrade signaling")),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`)})).catch((s=>{if(this.scheduler&&("TRACKER_EXPT"===s.code&&t.emitEvent(e.EXCEPTION,s),this.scheduler.notifyPeersLoaded(0),s.retry))if(s.immediate)this.resumeP2P();else{const e=m(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){clearInterval(this.checkConnsTimer),this.fetcher.postStatsWithBeacon(),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.peerPool.destroy(),this.peerPool=null,this.failedDCMap.clear(),this.notFoundDCSet.clear(),this.logUploader&&(this.logUploader.destroy(),this.logUploader=null),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")}isPeerConnectedOrFailed(e){return!e||(this.DCMap.has(e)||this.failedDCMap.has(e)||e===this.peerId)}_filterPeers(e){return e.filter((e=>!this.isPeerConnectedOrFailed(e.id)))}_tryConnectToAllPeers(){const{logger:e}=this,t=this.totalConns;if(!(t>=this.maxConnsActive))if(0!==this.peers.length){for(this._checkDCMap(),e.info(`try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${t}`),this.peersTemp=[];this.peers.length>0&&!this.isReachActiveLimit;){let t=this.peers.shift();const s=t.intermediator;if(!this.isPeerConnectedOrFailed(t.id)){if(!s||!this.DCMap.has(s)){let s=!1;if(this.signalerWs.connected||(s=!0,e.info(`skip peer ${t.id} without intermediator`)),[...this.DCMap.values()].filter((e=>!e.byPeerSignal&&!e.connected)).length>=this.maxPeersBySignalServer&&(s=!0,e.warn(`skip peer ${t.id} by signal server`)),s){this.peersTemp.push(t);continue}}e.debug(`create DataChannel ${t.id} intermediator ${s}`),this._createDatachannel(t.id,!0,s)}}this.peers.push(...this.peersTemp)}else e.info("no peers after filter")}_handleSendSignal(e,t){const s=e.remotePeerId;if(e.intermediator){const i=this.DCMap.get(e.intermediator);if(i){let r=!0;for(let e of t)i.sendMsgSignal(s,this.peerId,e)||(r=!1);if(r)return void(e.signalName=null);this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,e.signalName=this.signalerWs.sendSignalBatch(s,t,e.signalName)}_setupDC(t){t.on(e.DC_SIGNAL,(e=>{this._handleSendSignal(t,[e])})).on(e.DC_SIGNAL_BATCH,(e=>{this._handleSendSignal(t,e)})).on(e.DC_PEER_SIGNAL,(e=>{const s=e.to_peer_id||e.to,i=e.from_peer_id||e.from,r=e.action;if(s&&i&&r)if(s!==this.peerId){this.logger.info(`relay signal for ${i}`);const n=this.DCMap.get(s);if(n){if("signal"!==r)return void n.sendMsgSignalReject(s,i,e.reason,e.fatal);if(n.sendMsgSignal(s,i,e.data))return}t.sendMsgSignal(i,s)}else"signal"===r?this._handleSignalMsg(i,e,t.remotePeerId):this._handSignalRejected(i,e)})).once(e.DC_ERROR,((e,s)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${s}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCMap.set(t.remotePeerId,`DC_FAILED ${s}`),this._doSignalFusing(this.totalConns),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:s,data:i})=>{const{logger:r}=this,{remotePeerId:n,isInitiator:a}=t;if(s&&e&&a&&(this.failedDCMap.set(n,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!this.isReachActiveLimit&&!e&&a&&this._tryBackupSignal(t,n,i,t.signalName))return t._startTimer(),void r.warn(`${n} conn timeout, try backup signal`);this._destroyAndDeletePeer(n,!1),a&&this._doPeersRequest()})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.totalConns)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCMap.set(t.remotePeerId,"DC_CLOSE"),this._doPeersRequest()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler&&this.scheduler.handshakePeer(t,this._gatherPeersToSent(t))})).once(e.DC_METADATA,(e=>{const{scheduler:s}=this;if(!s)return;t.isInitiator||s.handshakePeer(t,this._gatherPeersToSent(t)),s.handleMetaData(t,e);const i=this.isReachActiveLimit;i||this._handleRequestedPeers(this._handleSharedPeers(t,e.shared_peers))>0&&this._tryConnectToAllPeers(),this.requestMorePeers(i);const r=this.totalConns;this._doSignalFusing(r),r>=this.maxConns&&this.fuseRate<0&&this.fetcher.postStats(!0)&&this.logger.warn(`peers reach ${r}, report`)}))}_doPeersRequest(){this.peers.length<this.maxConnsActive-this.DCMap.size&&this._gatherSharedPeersFromPeers(),(0===this.peers.length||this.totalConns<this.minConns)&&this.requestMorePeers(),this._tryConnectToAllPeers()}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate?(this.logger.warn("reach fuseRate, close signaler"),this.totalConns>0&&this.fetcher.postStats(!0),this.signalerWs.close()):!t&&e<=this.minConns&&!this.signalerWs.connecting&&this.signalerWs.reconnect()&&(this.logger.warn(`low conns ${e}, reconnect signaler`),this.fetcher.postStats(!0))}_initSignalerWs(t,s,i,r){const n=(e,t)=>{let s=`${e}?id=${this.peerId}&p=web&v=2.17.12&b=1`;return this.config.signalCompact&&(s=`${s}&c=1`),t&&(s=`${s}&token=${t}`),s};let a,o=n(t,i);if(s&&s!==t){let e=n(s,r);a=new ct(this.logger,this.config,o,e)}else a=new dt(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let s=e.action;const i=e.from_peer_id||e.from;if(i)switch(s){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`signal ${t} unknown action ${s}`)}else this.logger.warn("fromPeerId is missed")},a.onclose=()=>{this.connected=!1},a.onerror=t=>{t.message&&this.logger.warn(`signal err: ${t.message}`),t.message&&this.engine.emitEvent(e.EXCEPTION,Fe(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const s=`signaling ${e} rejected`;this.logger.warn(`${s}, reason ${t.reason}`);const i=this.DCMap.get(e);i&&!i.connected&&(i.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,s),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,s,i){return!(!(this.signalerWs.backupConnected&&e&&s.length>0&&"main"===i)||e.useBackupSignal)&&(e.intermediator=void 0,e.signalName=this.signalerWs.sendSignalBatch(t,s,"backup"),!0)}_handleSignalMsg(e,t,s,i){if(!this.scheduler)return;const{logger:r}=this;if(t.data){if(this.failedDCMap.has(e))return void this._sendSignalReject(e,`${e} ${this.failedDCMap.get(e)||"unknown"}`,s,i,!0);this._handleSignal(e,t.data,s,i)}else{const t=this.DCMap.get(e);if(!t)return;if(!this.isReachActiveLimit&&this._tryBackupSignal(t,e,t.signalMsgs,i))return void this.logger.warn(`${e} not found from ${i}, try backup signal`);if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),r.info(`signaling ${e} not found`);const{scheduler:n}=this;if(n.waitForPeer&&(n.waitingPeers--,0===n.waitingPeers&&n.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),s){const t=this.DCMap.get(s);t&&t.notFoundPeers.add(e)}else this.notFoundDCSet.add(e)}}_handleSignal(e,t,s,i){let r=t;"string"==typeof r?r=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:Pt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),s="O"===e[0];return{type:s?"offer":"answer",sdp:wt(t,s)}})(r):t=void 0;const n=r.type,{logger:a}=this;let o=this.DCMap.get(e);if(o){if(o.connected)return void a.info("datachannel had connected, signal ignored");if("offer"===n&&o.isInitiator){if(!(this.peerId>e))return void a.warn(`${e} signal type wrong ${n}, ignored`);a.warn(`${e} signal type wrong ${n}, convert to non initiator`),this._destroyAndDeletePeer(e,!1),o=this._createDatachannel(e,!1,s)}}else{if("answer"===n){const t=`${e} type wrong ${n}`;return a.warn(t),this._sendSignalReject(e,t,s,i),void this._destroyAndDeletePeer(e,!1)}if(a.debug(`receive node ${e} connection request`),this.DCMap.size>=this.maxConns){const t=`reach limit ${this.maxConns}`;return a.warn(t),void this._sendSignalReject(e,t,s,i,!0)}o=this._createDatachannel(e,!1,s)}o&&o.receiveSignal(r,t)}_createDatachannel(e,t,s){if(!this.fetcher)return;let i;if(t&&this.peerPool.available)i=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${i.signalMsgs.length}`),i.intermediator=s,i.assignPeerId(this.peerId,e);else{let r=this.config.trickleICE;this.overloaded&&(r=!1),i=new te(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:s,trickle:!s&&r})}return this.DCMap.set(e,i),this._setupDC(i),i}_sendSignalReject(e,t,s,i,r){if(this.signalRejectCache!==e){if(s){const i=this.DCMap.get(s);if(i&&i.sendMsgSignalReject(e,this.peerId,t,r))return}this.signalerWs.sendReject(e,t,r,i),this.signalRejectCache=e}}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this;if(this._checkDCMap(),this.isReachActiveLimit)return;this._gatherSharedPeersFromPeers();const s=this.peers.length,i=this.totalConns;i<this.minConns&&(0===s||i+s<=this.maxConnsActive)&&this.signalerWs.connected?(t.info(`requestMorePeers after delay ${e} peersNum ${i}`),this._requestPeersFromServer(i)):t.info(`skip requestMorePeers peersNum ${i} try peers ${s}`),this._tryConnectToAllPeers()}_requestPeersFromServer(e){const{logger:t}=this;this.failedDCMap.size>50&&(this.failedDCMap=new Map([...this.failedDCMap].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCMap.keys(),...this.notFoundDCSet.keys()],0===e).then((e=>{e&&e.peers&&(t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers())})).catch((e=>{t.error(`requestMorePeers error ${e}`)}))}_handleRequestedPeers(e=[],t=!1){if(this.fetcher){if(e.length>0){const s=function(e,t){const s=[],i=new Set;for(let t of e)i.has(t.id)||(i.add(t.id),s.push(t));const{asn:r,country:n}=t;if(!r||!n||s.length<2)return s;const a=s.filter((e=>!e.asn&&!e.country)),o=s.filter((e=>e.country===n&&e.asn!==r)),l=s.filter((e=>e.asn===r&&e.country===n)),h=s.filter((e=>!a.includes(e)&&!l.includes(e)&&!o.includes(e)));return l.concat(o).concat(a).concat(h)}(e,this.fetcher.announceInfo);return t?this.peers=s:this.fuseRate>0?this.peers=[...s,...this.peers]:this.peers=[...this.peers,...s],this.logger.info(`after filtered total ${s.length}`),s.length}return 0}}_destroyAndDeletePeer(e,t=!0){const s=this.DCMap.get(e);return!!s&&(s.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=p();for(let t of this.DCMap.values()){const s=e-t.timeJoin;e-t.timeJoin>20&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${s} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}_filterFullPeers(){return this.scheduler.getPeers().filter((e=>e.peersConnected<(this.fuseRate<0?e.mobileWeb?14:19:this.maxConns)&&!e.super))}_filterImmaturePeers(e,t,s){const i=[];return e.forEach((e=>{if(e.remotePeerId===t.remotePeerId||e.remotePeerId===this.peerId)return;if(!this.config.live&&(e.currentPos-t.currentPos>600||e.currentPos<t.currentPos))return;s-e.timeJoin>40&&i.push({id:e.remotePeerId,...e.region})})),i}_gatherPeersToSent(e){const t=this._filterFullPeers();return this._filterImmaturePeers(t,e,p())}_handleSharedPeers(e,t){const s=[];return t&&t.length>0&&(this.logger.info(`receive ${t.length} peers from ${e.remotePeerId}`),t.forEach((t=>{t.intermediator=e.remotePeerId})),s.push(...this._filterPeers(t))),s}_startCheckConnsTimer(){const{scheduler:e}=this;this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const t=this.scheduler.getStatsForPeer();let s=this.totalConns;const i=p(),r=this._filterFullPeers();e.getPeers().forEach((e=>{s>this.minConns+1&&(i-e.dataExchangeTs>120||i-e.gotStatsTs>=103)?(this.logger.warn(`close dead peer ${e.remotePeerId} level ${e.currentLevel}`),e.close(!1),s--):e.connected&&e.sendMsgStats(s,this._filterImmaturePeers(r,e,i),t)}))}),5e4)}_gatherSharedPeersFromPeers(){const e=[],t=new Set,s=this.scheduler.getPeers();x(s).forEach((s=>{const i=this._handleSharedPeers(s,s.currentSharedPeers).filter((e=>!t.has(e.id)&&(t.add(e.id),!0)));e.push(...i)})),e.length>0&&(this.logger.info(`gather shared peers total ${e.length}`),0===this._handleRequestedPeers(e,!0)&&s.forEach((e=>{e.clearCurrentSharedPeers()})))}}const Ct=Dt;class kt extends ne{constructor(e={},t=null){if(super(e),e.validateSegment||(e.validateSegment=function(e,t){return!0}),this.hlsjs=t,this.config=Object.assign({useDiskCache:!e.live},ge,e),t){this.HLSEvents=t.constructor.Events;const e=t.constructor.version;this.hlsjsVersion=e,this.config.isHlsV0=e&&"0"===e.split(".")[0]}this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t}=this.config,s=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(s=this.makeChannelId(e,t));return{channelIdMaker:s,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo}}}setupElectron(){this.browserInfo.device===J.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();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=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(e){const{logger:s,config:i}=this;if(self.indexedDB&&i.useDiskCache&&!i.live){const e=new Ce(this,i);try{await e.setupStore(),this.bufMgr=e}catch(e){s.warn(e),this.bufMgr=new xe(this,i)}}else this.bufMgr=new xe(this,i);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid");"SegmentStore"===this.bufMgr.name&&(this.removeAllListeners(t.BM_FATAL_ERROR),this.once(t.BM_FATAL_ERROR,(()=>{s.warn("SegmentStoreFatalError, switch to SegmentCache"),this.bufMgr.destroy(),this.bufMgr=new xe(this,i),e&&e(this.bufMgr)})))}generateTag(){let e=(0,J.getBrowser)();return e.includes("iPhone")&&"HlsSwP2pEngine"===this.engineName&&(e=`${e}_p`),this.playerName&&(e=`${e}_${this.playerName}`),e}async _init(e,t,s){const{logger:i,config:r}=this;if(!ne.isSupported())throw new Error("webrtc is not supported");await this.initSegmentManager((e=>{if(this.tracker){const{scheduler:t}=this.tracker;t.bufferManager=e,t.bitset.clear()}})),s.live||this.media&&(s.pos=Math.round(this.media.currentTime)),s.tag=void 0===r.tag?this.generateTag():r.tag;let n=new it(this,r.token,encodeURIComponent(e),r.announce||"",s);this.fetcher=n,this.tracker=new Ct(this,n,t,r),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?ce:de)}_onHlsError(e,s){if(!s||!this.hlsjs)return;const{logger:i,tracker:r,config:n}=this;if(!i)return;const a=`${s.type} fatal ${s.fatal} details ${s.details} reason ${s.reason}`;if(s.fatal?i.error(a):i.warn(a),"networkError"===s.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:o}=this.browserInfo,l=`${o||""} hlsjs ${this.hlsjsVersion} ${location.href}`,h=this.hlsjs.constructor.ErrorDetails;switch(s.details){case h.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),r&&r.scheduler){const e=r.scheduler;i.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case h.INTERNAL_EXCEPTION:if(s.event&&"demuxerWorker"!==s.event){s.error||(s.error={});const e=`${s.error.message} event ${s.event} ${l}`;i.error(`INTERNAL_EXCEPTION event ${s.event} err ${s.error.message}`),this.emitEvent(t.EXCEPTION,Fe(s.error,"HLSJS_EXPT")),i.report(e,s.event,this.peerId,"2.17.12")}break;default:const e=s.details===h.FRAG_PARSING_ERROR;if(s.fatal||e){"mediaError"===s.type&&r&&r.scheduler&&r.scheduler.disconnectLoadingPeer(void 0,this.peerId).then((e=>{e&&r.scheduler.clearCache()}));const e=`${s.type} ${s.details} ${s.err||""} ${l}`;i.report(e,s.details,this.peerId,"2.17.12")}}}}class Mt{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=o.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class xt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[xt.ElementaryStreamTypes.AUDIO]:!1,[xt.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=o.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 s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let s=e;return e&&e.method&&e.uri&&!e.iv&&(s=new Mt,s.method=e.method,s.baseuri=e.baseuri,s.reluri=e.reluri,s.iv=this.createInitializationVector(t)),s}}class Ot{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 Ft=/^(\d+)x(\d+)$/,Nt=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class $t{constructor(e){"string"==typeof e&&(e=$t.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 s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}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=Ft.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,s={};for(Nt.lastIndex=0;null!==(t=Nt.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),s[t[1]]=e}return s}}const Bt=$t,Ut={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}};const Gt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Ht=/#EXT-X-MEDIA:(.*)/g,Vt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),Wt=/(?:(?:#(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?/,qt=/\.(mp4|m4s|m4v|m4a)$/i;class jt{static findGroup(e,t){if(!e)return null;let s=null;for(let i=0;i<e.length;i++){const r=e[i];r.id===t&&(s=r)}return s}static convertAVC1ToAVCOTI(e){let t,s=e.split(".");return s.length>2?(t=s.shift()+".",t+=parseInt(s.shift()).toString(16),t+=("000"+parseInt(s.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let s,i=[];function r(e,t){["video","audio"].forEach((s=>{const i=e.filter((e=>function(e,t){const s=Ut[t];return!!s&&!0===s[e.slice(0,4)]}(e,s)));if(i.length){const r=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${s}Codec`]=r.length>0?r[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(Gt.lastIndex=0;null!=(s=Gt.exec(e));){const e={},n=e.attrs=new Bt(s[1]);e.url=jt.resolve(s[2],t);const a=n.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=n.decimalInteger("AVERAGE-BANDWIDTH")||n.decimalInteger("BANDWIDTH"),e.name=n.NAME,r([].concat((n.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=jt.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,s,i=[]){let r,n=[],a=0;for(Ht.lastIndex=0;null!==(r=Ht.exec(e));){const e={},o=new Bt(r[1]);if(o.TYPE===s){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=s,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=jt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=jt.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,n.push(e)}}return n}static parseLevelPlaylist(e,t){let s,i,r=0,n=0,a=new Ot(t),o=new Mt,l=0,h=null,d=new xt,c=null;for(Vt.lastIndex=0;null!==(s=Vt.exec(e));){const e=s[1];if(e){d.duration=parseFloat(e);const t=(" "+s[2]).slice(1);d.title=t||null,d.tagList.push(t?["INF",e,t]:["INF",e])}else if(s[3]){if(Number.isFinite(d.duration)){const e=r++;d.start=n,d.levelkey=o,d.sn=e,d.cc=l,d.baseurl=t,d.relurl=(" "+s[3]).slice(1),Kt(d,h),a.fragments.push(d),h=d,n+=d.duration,d=new xt}}else if(s[4]){if(d.rawByteRange=(" "+s[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(d.lastByteRangeEndOffset=e)}}else if(s[5])d.rawProgramDateTime=(" "+s[5]).slice(1),d.tagList.push(["PROGRAM-DATE-TIME",d.rawProgramDateTime]),null===c&&(c=a.fragments.length);else{for(s=s[0].match(Wt),i=1;i<s.length&&void 0===s[i];i++);const e=(" "+s[i+1]).slice(1),n=(" "+s[i+2]).slice(1);switch(s[i]){case"#":d.tagList.push(n?[e,n]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":r=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 u=new Bt(e),f=u.enumeratedString("METHOD"),g=u.URI,p=u.hexadecimalInteger("IV");f&&(o=new Mt,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 Bt(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let h=new Bt(e);d.relurl=h.URI,d.rawByteRange=h.BYTERANGE,d.baseurl=t,d.sn="initSegment",a.initSegment=d,d=new xt,d.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${s}`)}}}return d=h,d&&!d.relurl&&(a.fragments.pop(),n-=d.duration),a.totalduration=n,a.averagetargetduration=n/a.fragments.length,a.endSN=r-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>qt.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),d=new xt,d.relurl=a.fragments[0].relurl,d.baseurl=t,d.level=id,d.sn="initSegment",a.initSegment=d,a.needSidxRanges=!0),c&&function(e,t){let s=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(a.fragments,c),a}}function Kt(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)}class zt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const s=Number(e);if(s<0)continue;const i=new Map;if(t[e])for(let s of t[e])i.set(s,{state:d.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(s,i)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,s,i=d.ANY){if(t<0)return!1;const r=this._createOrGetSet(t).get(e);return!!r&&((!s||!r.segId||r.segId===s)&&(i===d.ANY||r.state===i))}has(e,t,s=d.ANY){return this.hasWithId(e,t,void 0,s)}hasCompleteOr(e,t,s=d.COMPLETE){const i=this._createOrGetSet(t).get(e);return!!i&&(i.state===d.COMPLETE||i.state===s)}getObj(e,t){let s=this._createOrGetSet(t).get(e);return s||(s={}),s}getSegId(e,t){return this.getObj(e,t).segId}getSize(e,t){return this.getObj(e,t).size}getState(e,t){return this.getObj(e,t).state}delete(e,t){return this._createOrGetSet(t).delete(e)}deleteOlderThan(e,t){const s=this._createOrGetSet(t);s.forEach(((t,i)=>{i<=e&&s.delete(i)}))}add(e,t,s,i,r){if("number"!=typeof(n=e)||n%1!=0)return;var n;this._createOrGetSet(t).set(e,{state:i,segId:s,size: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,s)=>{e[s]=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-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[s,i]of e)i.state===d.COMPLETE&&t.push(s);return t}}class Yt{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 s=this._createOrGetMap(t);if(s.has(e)){let t=s.get(e);1===t?s.delete(e):s.set(e,t-1)}}incre(e,t){const s=this._createOrGetMap(t);if(s.has(e)){let t=s.get(e);s.set(e,t+1)}else s.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}}const Xt=class{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))}},Qt=Symbol("shareOnly");class Jt extends(n()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Xt,this.fragLoading=!1,this._setupEngine&&this._setupEngine(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[Qt]=!1,this.downloadOnly=!1,this.loadedPeerNum=0}get isMobileNet(){return this.engine.isMobileNet}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}chokePeerRequest(t){const s={event:e.DC_CHOKE};t?t.sendJson(s):this._broadcastToPeers(s)}unchokePeerRequest(t){const s={event:e.DC_UNCHOKE};t?t.sendJson(s):this._broadcastToPeers(s)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[Qt]=!0}deletePeer(e){e.downloading&&this._handlePieceAborted(e.remotePeerId),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[Qt]&&(e.choked=!0);const s=this.peerManager.getPeerIds();this._peersStats(s);const{asn:i,country:r}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${r||""} asn ${i||""}, now has ${s.length} peers`)}hasPeer(e){return this.peerManager.hasPeer(e)}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),t<this.peersNum){const t=this.peerManager.getPeers(),s=t.filter((e=>e.downloading));e.warn(`downloading: ${s.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of s)e.warn(`${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:e,segId:t,next:s,level:i})=>{this._broadcastLost(e,t,i),this.onBufferManagerLost(e,t,s,i)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,s,i,r){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:s||void 0,level:i},r)}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearTimeout(this.checkTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:s}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),s.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{s.info(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),this._handlePieceAborted(t.remotePeerId),this.config.live&&this.checkPeers&&this.checkPeers()})).on(e.DC_DISCONNECT,(()=>{this.peersNum>=4&&(this.logger.warn(`close disconnected peer ${t.remotePeerId}`),t.close(!1))}))}_broadcastToPeers(e,t){for(let s of this.getPeers())t&&s===t||s.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;P(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(s=this.loadedPeerNum)?3:.5*s+1.67);var s;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const s=this.requestingMap.get(e);if(s)return void s.removeStreamListener(t);const i=this.segmentBuilderMap.get(e);i&&i.removeStreamListener(t)}setTargetPeersFromGroup(e,t,s,i){if(e.hasReversePeer){if((s=t.concat(s)).length>0)return this.targetPeers.forwardPeer=s[0],!0}else if(e.hasForwardPeer&&(i=t.concat(i)).length>0)return this.targetPeers.reversePeer=i[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=D(t,s,i),this.targetPeers.some((e=>!!e)))}}const Zt=Jt;class es extends(n()){constructor(){super(),this.internalMap=new Map}has(e){return this.internalMap.has(e)}set(e,t){this.internalMap.set(e,t),T(this.internalMap,13,(e=>{e&&e.destroy()}))}get(e){return this.internalMap.get(e)}delete(e){const t=this.internalMap.get(e);t&&(t.destroy(),this.internalMap.delete(e))}get size(){return this.internalMap.size}clear(){this.internalMap.clear(),this.removeAllListeners()}get activePeers(){let e=0;return[...this.internalMap.values()].forEach((t=>{t.hasForwardPeer&&!t.forwardCanceled&&(e+=1),t.hasReversePeer&&!t.reverseCanceled&&(e+=1)})),e}}const ts=(e,t,s,i,r=!1)=>{const[n,a,o]=ss(e,t,s,i);return r&&n.length>=1?I(n[0]):n.length>=2?[n[0],n[1]]:D(n,a,o)},ss=(e,t,s,i)=>{const r=[],{COMPLETE:n,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=d;return[n,a,o].forEach((n=>{r.push(is(e,n,t,s,i))})),r},is=(e,t,s,i,r)=>e.filter((e=>e.bitset.hasWithId(s,i,r,t))),rs=0,ns=1,as=2,os=3;class ls extends(n()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,s)=>{e+=`${s}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0,this.emit("loadend")}send(){}_emitEvent(e){this.emit(e,{type:e,target:this})}}const hs=/(\d+)-(\d+)\/(\d+)/;function ds(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class cs{constructor(e){this.fetchSetup=e.fetchSetup||us,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=C(),this.packetSize=c,this.fakeXhr=new ls}destroy(){this.destroyed=!0,this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.xhrSetup=this.fakeXhr=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){if(this.destroyed)return;const i=this.stats;i.trequest=i.loading.start;let r=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return s}(e,(this.controller||{}).signal);const n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=s.onUpdate,d=s.onBodyStart;this.context=e,this.config=t,this.callbacks=s,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),r=function(e,t){e.withCredentials&&(t.credentials="include");for(let[s,i]of e.headers)t.headers.set(s,i);return t}(this.fakeXhr,r)),this.request=this.fetchSetup(e,r),clearTimeout(this.requestTimeout),t.timeout=o&&Number.isFinite(o)?o:l,this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.destroyed||(this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),s.onTimeout&&s.onTimeout(i,e,this.response))}),this.fakeXhr.timeout||t.timeout);const c="then"in(u=this.request)&&u.then instanceof Function?this.request.then(self.fetch):self.fetch(this.request);var u;const{fakeXhr:f}=this;f.readyState=f.OPENED,f.emit("readystatechange"),f._emitEvent("loadstart"),c.then((r=>{this.response=this.loader=r;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout&&s.onTimeout(i,e,this.response)}),l-(a-i.loading.start)),!r.ok){const{status:e,statusText:t}=r;throw new fs(t||"fetch, bad network response",e,r)}i.tfirst=i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=hs.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(r.headers)||i.total;let o=0;try{const e=r.headers.get("Content-Range").split("/");2===e.length&&(o=parseInt(e[1],10))}catch(e){}const{fakeXhr:c}=this;return c.readyState=c.HEADERS_RECEIVED,c.responseHeaders=r.headers,c.emit("readystatechange"),h&&"0"!==i.total?(d&&d(i.total,o),this.loadProgressively(r,i,e,h)):(c.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),n?r.arrayBuffer():"json"===e.responseType?r.json():r.text())})).then((t=>{const{response:r}=this;clearTimeout(this.requestTimeout),i.tload=i.loading.end=Math.max(performance.now(),i.loading.first);const n=t[a];n&&(i.loaded=i.total=n);const o={url:r.url,data:t,code:r.status};s.onProgress&&s.onProgress(i,e,t,r),s.onSuccess&&s.onSuccess(o,i,e,r)})).catch((t=>{if(clearTimeout(this.requestTimeout),i.aborted)return;const r=t&&t.code||0,n=t?t.message:null;s.onError&&s.onError({code:r,text:n},e,t?t.details:null,i)}))}loadProgressively(e,t,s,i){const r=e.body.getReader();let n=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>r.read().then((({value:s,done:r})=>{const{fakeXhr:u}=this;if(u.readyState!==u.LOADING&&(u.readyState=u.LOADING,u.emit("readystatechange")),s&&(n+=s.length),r){if(l.byteLength>0)if(n<=this.packetSize){const e=(0,a.h)(n);l.copy(e,0,o*this.packetSize,l.byteLength),i(e,!0)}else{const e=function(e,t){const s=e.byteLength-t,i=[];let r=t,n=Math.floor(s/c),o=s%c;for(let t=0;t<n;t++){const t=(0,a.h)(c);e.copy(t,0,r,r+c),i.push(t),r+=c}if(o>0){const t=(0,a.h)(o);e.copy(t,0,r,r+o),i.push(t)}return i}(l,o*this.packetSize);for(let t=0;t<e.length;t++)i(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:s}=this,{status:r,statusText:h,url:d}=e;return s.readyState=s.DONE,s.responseText=r,s.status=h,s.responseURL=d,s.responseType="arraybuffer",s.response=t,s.emit("readystatechange"),s._emitEvent("load"),s._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=s.length,u.emit("progress",new ProgressEvent("progress",{lengthComputable:!0,loaded:t.loaded,total:t.total})),this.callbacks.onLoaded&&this.callbacks.onLoaded({total:t.total,loaded:t.loaded,first:!h},this.context),h=!0,l=a.h.concat([l,s]),n>=this.packetSize){n-=this.packetSize;const e=(0,a.h)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,i(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function us(e,t){return new self.Request(e.url,t)}class fs extends Error{constructor(e,t,s){super(e),this.code=t,this.details=s}}class gs extends(n()){constructor(e,t,s=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=s,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.proxied=!1,this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.forwardCanceled=!1,this.reverseCanceled=!1,this.firstReceived=!1,this.alreadyOutput=!1,this.pieceMsg={}}get isDownloading(){return this.timeReceivePiece>0}get isAlmostDeadline(){return this.rangeRequesting||this.alreadyOutput}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}get streamListeners(){return[...this.reverseStreamListeners,...this.forwardStreamListeners].length}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg,s=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let i of s){const{handler:s}=i;s(e,t,!0,"aborted by synthesizer")}this._resetStreamListeners()}_resetStreamListeners(){this.reverseStreamListeners.length=0,this.forwardStreamListeners.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,s){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:s,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:s}=this.pieceMsg,i=i=>i.filter((i=>i.peerId!==e||(i.handler(t,s,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=i(this.forwardStreamListeners),this.reverseStreamListeners=i(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let s=performance.now();e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.firstPieceTimer=setTimeout((()=>{if(this.firstReceived)return;const e=()=>{this.logger.warn(`switch to http, firstReceived ${this.firstReceived}`),this._handleTimeout(!1)};if(this.timeReceivePiece>0){const t=(this.timeReceivePiece-s)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=s+e,this._startTimer(e,t))}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.proxied&&(this.proxied=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}get hasForwardPeer(){return!!this.forwardPeer}get hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}get isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}get isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1,t),!0))}setReversePeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0,t),!0))}setPeer(e,t,s){return t?this.setReversePeer(e,s):this.setForwardPeer(e,s)}deletePeer(e){const t=e===this.reversePeer;this._detachPeer(e),t?this.reversePeer=null:this.forwardPeer=null,(this.isEmpty||this.deadline>0)&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}get hasPartialBuffer(){return this.hasForwardBuffer||this.hasReverseBuffer}get hasForwardBuffer(){return this.forwardOffset>=0}get hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments}get isForwardBufferFull(){return this.pieceMsg&&this.forwardOffset>=this.pieceMsg.attachments-1}get isReverseBufferFull(){return this.reverseOffset<=0}_cancelP2p(e=!1){const{seg_id:t,sn:s,level:i}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(s,i,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(s,i,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){this._notifyStreamListenersAbort(),this.removeAllListeners(),this.destroyed=!0,this._detachPeer(this.forwardPeer),this.forwardPeer=null,this.forwardOffset=-1,this._detachPeer(this.reversePeer),this.reversePeer=null,this.reverseOffset=1e4,this.bufArr=[],this.forwardStreamListeners=[],this.reverseStreamListeners=[],this._abortLoading()}_abortLoading(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._cancelP2p(),this.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort(),this.httpLoader=void 0)}_detachPeer(t){if(!t)return;const s=t===this.reversePeer?this.reverseEvents:this.forwardEvents;s&&s&&t.off(e.DC_PIECE_DATA,s.onPieceData).off(e.DC_PIECE,s.onPiece).off(e.DC_PIECE_NOT_FOUND,s.onPieceNotFound).off(e.DC_PIECE_ABORT,s.onPieceAbort)}_receivePacket(t,s,i,r=!0){const{seg_id:n,sn:o,level:l,size:h,ext:d}=this.pieceMsg,c=s-1;if(this.bufArr[c]?(this.logger.warn(`syn bufArr ${n} already has ${c} size ${i.byteLength}`),this.bufArr[c]=i):(r?this.p2pLoaded+=i.byteLength:this.httpLoaded+=i.byteLength,this.emit(e.SYN_PROGRESS,{total:h,loaded:this.p2pLoaded+this.httpLoaded,first:!this.firstReceived,segId:n,sn:o}),this.firstReceived=!0,this.bufArr[c]=i,t?this.reverseOffset=c:this.forwardOffset=c,this._notifyStreamListeners(t,i,c)),this.forwardOffset!==this.reverseOffset-1)return!0;this.rangeRequesting||(this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0)),clearTimeout(this.timer),this._notifyStreamListenersRemain();const u=performance.now()-this.timeStart,f=h/u;let g=a.h.concat(this.bufArr);const p=g.byteLength;if(p===h){if(this.alreadyOutput)return!1;this.alreadyOutput=!0,this._abortLoading();let t=g.buffer;const s=new Q(o,n,t,this.getFromPeerId(),l,d);this.emit(e.SYN_OUTPUT,s,{speed:f,time:u,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${n} expectedSize ${h} != byteLength ${p} forward ${this.forwardOffset} reverse ${this.reverseOffset}`);for(let e=0;e<this.bufArr.length;e++)this.logger.error(`piece ${e} size ${this.bufArr[e].byteLength}`);this._onSynError(rs),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:s,sn:i}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${s||i} size not match ${t} ${e}`),!1)}_setupPeer(t,s,i){const{logger:r}=this;0===this.timeStart&&(this.timeStart=performance.now()),i&&!this.pieceMsg.size&&(this.pieceMsg.size=i);const n=(e,s,i,n,a,o)=>{if(this.destroyed)return;if(!this._validateMsg(e,o.level,s))return void r.error(`onPieceData ${s||e} size ${i.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(n<this.pieceMsg.attachments&&i.byteLength!==c)return r.error(`${s} dataSn ${n} size is ${i.byteLength}`),this._onSynError(rs),void this._disconnectPeers();const{reverse:l}=o;this._receivePacket(l,n,i)&&!this.waitingRemain&&!this.rangeRequesting&&this.deadline>0&&this._shouldSwitch()&&(r.warn("should switch to http"),clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._handleTimeout(!1,!1))},a=e=>{if(this.destroyed)return;const{attachments:s,size:i,sn:n,level:a,seg_id:o,ext:l={}}=e;let h=!0;(i<=999||!this._validateMsg(n,a,o))&&(r.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),h=!1),this._checkPieceSize(i)||(h=!1);const{ext:d}=this.pieceMsg;if(d&&l.hash&&d.hash&&l.hash!==d.hash&&(this.logger.warn(`syn ${o||n} hash not match ${l.hash} ${d.hash}`),h=!1),!h)return t.cancelDownload(n,a,o),void this.deletePeer(t);0===this.bufArr.length?(this.pieceMsg={...this.pieceMsg,seg_id:o,size:i,attachments:s,ext:l},this.reverseOffset=s,this.bufArr=new Array(s),this.timeReceivePiece=performance.now()):!this.pieceMsg.ext.hash&&l.hash&&(this.pieceMsg.ext.hash=l.hash)},o=e=>{this.destroyed||this.deletePeer(t)},l=()=>{this.destroyed||this.deletePeer(t)},h={onPieceData:n,onPiece:a,onPieceNotFound:o,onPieceAbort:l};s?this.reverseEvents=h:this.forwardEvents=h,t.on(e.DC_PIECE_DATA,n).once(e.DC_PIECE,a).once(e.DC_PIECE_NOT_FOUND,o).once(e.DC_PIECE_ABORT,l)}_shouldSwitch(){const e=c,t=this.pieceMsg.size-e*this.loadedPackets;return this.coordinator.shouldSwitchToHttp(t,this.deadline,this.p2pSpeed,e,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}get loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(e=!1,t=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:s,size:i,attachments:r}=this.pieceMsg;if(!i||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${s} url ${this.url}`),void this._onSynError(rs);if(e&&this.timeReceivePiece>0&&r){this.logger.warn(`syn ${this.loadedPackets} of ${r} packets loaded`);const e=this.httpLoadTime>3e3?3e3:this.httpLoadTime;if(this.shouldWaitForRemain(e))return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(t){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const s=e.currentLoadSpeed(),i=t.currentLoadSpeed();return s===i?e.timeSendRequest-t.timeSendRequest:s-i})).shift();e&&e.loadtimeout()}if((this.rangeSupported||!this.hasPartialBuffer)&&this.url)return this._cancelP2p(!0),this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this._onSynError(os)}shouldWaitForRemain(e){if(this.isEmpty||e<=0)return!1;let t=performance.now()-this.timeStart;return t<500||t<800&&this.timeReceivePiece>0||this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece)return!1;const t=this.p2pSpeed,s=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${s}`),t>=s}minRequiredSpeed(e){let t=0;return[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(t+=e.loadedBytes())})),(this.pieceMsg.size-t)/e}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}getStreamInfo(e){const t=e?this.reverseBufList:this.forwardBufList;let s,i;return t.length<this.pieceMsg.attachments?(s=this.isFull?"WaitPartialDouble":"WaitPartialSingle",i=1):(s=this.isFull?"SynFullDouble":"SynFullSingle",i=0),{from:s,incompletes:i,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting||this.alreadyOutput)return;const{size:e,seg_id:t}=this.pieceMsg,{logger:s}=this,i=this.rangeEnd>0?this.rangeEnd-1:0;let r=this.forwardOffset;const n=performance.now();this.rangeRequesting=!0;let a=he(r,this.reverseOffset,e,this.rangeStart,i);const o=a.rangeEnd-a.rangeStart;s.info(`listeners ${this.streamListeners} continue download ${t} from ${this.url} range: ${a.rangeStart}-${a.rangeEnd}`),this.hasPartialBuffer||(a={});const l=new cs({xhrSetup:this.xhrSetup});this.httpLoader=l;let d={url:this.proxied?g(this.url,h,!0):this.url,...a};let c,u=r+1;const f={onUpdate:(e,t,i)=>{if(!this.destroyed){if(i)return s.warn("httpLoader aborted"),void(this.alreadyOutput||this._onSynError(ns));if(t){const e=c/(performance.now()-n);this.coordinator.addHttpSpeed(e),this.httpLoader=void 0}this.bufArr[u]||this._receivePacket(!1,u+1,e,!1),u++}},onBodyStart:(e,i)=>{if(0===i&&s.warn(`range request fileSize ${i}`),this.destroyed)return;const{size:r}=this.pieceMsg;if(c=e,e!==r||0!==i&&i!==r){let t=!1;i>0&&i!==r?(s.error(`onBodyStart fileSize ${i} != ${r}`),t=!0):e!==o&&(s.error(`onBodyStart size ${e} != expectedSize ${o}`),t=!0),t&&"{}"!==JSON.stringify(a)&&this._onSynError(ns)}else s.warn(`syn range request ${t} resp whole ts`),u=0},onError:e=>{this.destroyed||(s.error(`httpLoader error ${e.text}`),this._onSynError(ns))},onTimeout:()=>{this.destroyed||(s.warn("httpLoader timeout"),this._onSynError(as))}};l.load(d,{timeout:15e3},f)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class ps extends gs{constructor(e,s,i,r,n,a=!1,o){super(e,s,a,o),this.pieceMsg={event:t.DC_PIECE,sn:i,level:r,seg_id:n},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,s){const{sn:i,seg_id:r,attachments:n}=this.pieceMsg,a=e&&0===s||!e&&s===n-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:s}=e;s(i,r,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,s){return(!this.pieceMsg.seg_id||s===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}_onSynError(e){const{sn:s,level:i}=this.pieceMsg;this.forwardPeer&&this.forwardPeer.bitset.delete(s,i),this.reversePeer&&this.reversePeer.bitset.delete(s,i),this.emit(t.SYN_ERROR,this.pieceMsg,e)}}class ms{constructor(){this.meanHttpSpeed=0,this.loaderHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=this._cal(this.meanHttpSpeed,e)}addLoaderHttpSpeed(e,t){t&&e&&(this.loaderHttpSpeed=this._cal(this.loaderHttpSpeed,t/e))}getMeanTimeToLoaded(e){return this.loaderHttpSpeed?e/this.loaderHttpSpeed:500}shouldSwitchToHttp(e,t,s,i,r){if(this.meanHttpSpeed<=0)return!1;if(s>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*r>=e)return!1;return((r+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-s)*s<i}_cal(e,t){return.4*e+.6*t}}class vs extends Zt{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new zt(t.live||!1),this.bitCounts=new Yt,this.requestingMap=new es,this.segmentBuilderMap=new es,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new ms,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=10:(this.maxPrefetchCount=150,this.startCheckPeersTimer())}handshakePeer(e,t=[]){this._setupDC(e);const{asn:s,country:i}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:s,country:i},this.isMobileNet,t)}_receiveDCHave(e,t,s,i,r){this.bitset.has(e,t)||this.bitCounts.incre(e,t),r>i.currentLost&&(i.bitset.deleteOlderThan(r,t),i.currentLost=r)}_setupDC(e){super._setupDC(e),e.on(t.DC_HAVE,(t=>{if(e.bitset&&t.sn>=0){const{sn:s,level:i,complete:r,seg_id:n,size:a,curr_lost_sn:o}=t,l=r?d.COMPLETE:d.PARTIAL_FORWARD;e.bitset.add(s,i,n,l,a),this._receiveDCHave(s,i,n,e,o),e.isAvailableUrgently&&this._handleDCHave(e,s,i,n,a,l)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:s,level:i,seg_id:r,size:n,curr_lost_sn:a}=t;e.bitset.hasCompleteOr(s,i,d.PARTIAL_REVERSE)||e.bitset.add(s,i,r,d.PARTIAL_REVERSE,n),this._receiveDCHave(s,i,r,e,a),e.isAvailableUrgently&&this._handleDCHave(e,s,i,r,n,d.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:s,level:i}=t;e.bitset.has(s,i)&&(e.bitset.delete(s,i),this.bitCounts.decre(s,i))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.requestingMap.has(ue(e.sn,e.level))&&this.notifyAllPeers(e.sn,e.level,e.seg_id,e.size,e.reverse?d.PARTIAL_REVERSE:d.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:s,level:i}=t,r=ue(s,i);this.removeStreamListener(r,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:s,level:i}=t;e.bitset.delete(s,i),this.bitCounts.decre(s,i),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:s}=this,{sn:i,level:r,reverse:n}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(i));const o=()=>{this.bitset.delete(i,r),e.sendPieceNotFound(i,a,{level:r}),this._broadcastLost(i,a,r,e)},l=await this.bufMgr.getSegById(a),h=ue(i,r),d=this.requestingMap.get(h);let c=!1;d&&d.isDownloading&&(c=!0);const u=this.segmentBuilderMap.get(h);if(l)if(s.info(`found seg ${a} from bufMgr`),l.level===r){let t="SegmentStore"===this.bufMgr.name?"Disk":"Cache";l.ext.from&&l.ext.from.length<2500&&(t=`${l.ext.from}-${t}`),e.sendBuffer(l.sn,l.segId,l.data,{from:t,level:l.level,reverse:n,hash:l.ext.hash})}else o();else if(!n&&u)s.info(`peer request ${i} wait from builder, sent ${u.bufferList.length}`),w(e,u,u.pieceMsg,u.bufferList,u.source,1);else if(c){s.info(`syn had ${d.loadedPackets} packets, wait remain from upstream ${d.getFromPeerId()}`);const t={...d.pieceMsg,reverse:n},{from:i,incompletes:r,bufferList:a}=d.getStreamInfo(n);w(e,d,t,a,i,r)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new zt(this.config.live,t.field);for(let e in t.field){const s=Number(e);if(s<0)continue;t.field[s].forEach((e=>{this.bitset.has(e,s)||this.bitCounts.incre(e,s)}))}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)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const s=Number(e),i=t[s];i&&i.forEach((e=>{this.bitCounts.decre(e,s)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,s,i){const{logger:r,config:n}=this;let a=1e3*(i-n.httpLoadTime);this.allowP2pLimit=n.httpLoadTime+1.5,r.info(`bufferedDuration ${1e3*i} remainLoadTime ${a} allowP2pLimit ${1e3*this.allowP2pLimit}`);const o=ue(e,t),l=this.requestingMap.get(o);if(l){const n=l.segId;if(n&&n!==s)return r.warn(`syn segId ${n} not match ${s}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,s,i);if(!l.shouldWaitForRemain(a)){if(r.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const i=this.peerManager.getPeersOrderByWeight();let[n,o,h]=ss(i,e,t,s);return!!this.setTargetPeersFromGroup(l,n,o,h)||(l.hasReversePeer||l.hasPartialBuffer||a>1e3*(this.allowP2pLimit+1))&&this.httpRangeSupported}return r.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,s,i)}_searchAvailablePeers(e,t,s,i){if(i<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const r=this.peerManager.getPeersOrderByWeight(),[n,a]=ts(r,e,t,s);return this.targetPeers={forwardPeer:n,reversePeer:a},[n,a].some((e=>!!e))}reportTraffic(e,t,s){const{fetcher:i}=this.engine;i&&(e>0&&i.reportFlow(e),t>0&&i.reportDCTraffic(t,s))}notifyAllPeers(e,t,s,i,r=d.COMPLETE){if(!s)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:n}=this.config;if(this.bitset.has(e,t,r))return;const a=((e,t,s)=>`${e}-${t}-${s}`)(e,t,r);let o;r!==d.PARTIAL_REVERSE&&(o=r===d.COMPLETE);const l=this.currLostSN>0&&o&&n?this.currLostSN:void 0,h=this.requestingMap.get(ue(e,t));for(let c of this.getPeers())h&&h.hasPeer(c)||c.notifySet.has(a)||c.bitset.hasCompleteOr(e,t,r)||(c.sendMsgHave(e,s,{level:t,reverse:r===d.PARTIAL_REVERSE,complete:o,size:i,curr_lost_sn:l}),c.notifySet.add(a),n&&_(c.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:s}=this;if(!this.hasPeers)return;const i=t.live;if(this.fragLoading&&!i)return void e.info("loading urgently, skip prefetch");const{currentLevel:r}=s;if(0===this.bitCounts.size(r))return;if(!i&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;let n=this.peerManager.getPeersOrderByWeight();if(0===n.length)return;let a=0,{prefetchNum:o,endSN:l,startSN:h}=t;if(!i){const t=this.requestingMap.size,s=this.requestingMap.activePeers;if(s>=o)return void e.warn(`requestingMap size ${t} activePeers ${s}`);o-=s}if(this.getBufferedDuration()<this.allowP2pLimit){if(!i)return;o=1}let c=0,u=this.loadingSN+1;if(this.prefetchOnly&&(u+=2),!i)if(this.loadingSN>=l&&!this.bufMgr.overflowed)u=h;else{const e=Math.min(...n.filter((e=>e.endSN>=u)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;u<e&&(u=e)}for(;a<o&&c<this.maxPrefetchCount&&(i||!(u>l))&&!(i&&u>this.loadingSN+2);){if(this.bitset.has(u,r)){u++;continue}const t=ue(u,r),s=this.requestingMap.get(t);if(this.bitCounts.has(u,r)){if(s){for(let e of n)if(e.bitset.has(u,r)){const{state:t,segId:i,size:n}=e.bitset.getObj(u,r);if(this._trySetPeerForSyn(s,e,i,u,r,n,t))break}}else{let s=[null,null];if(i)s=ts(n,u,r,void 0,!0);else for(let e of n)if(e.bitset.has(u,r)){const t=e.bitset.getState(u,r);let i;i=t===d.COMPLETE?0===m(0,1):t===d.PARTIAL_REVERSE,s[i?1:0]=e;break}if(s.some((e=>!!e))){const i=new ps(this.coordinator,this.logger,u,r,void 0,this.httpRangeSupported);this._setupSynthesizer(i),this.requestingMap.set(t,i),s.forEach(((t,s)=>{if(t&&a<o){const n=1===s,o=t.bitset.getSize(u,r);i.setPeer(t,n,o)&&(a++,t.requestDataBySN(u,!1,{level:r,reverse:n}),e.info(`request prefetch ${u} level ${r} from peer ${t.remotePeerId} downloadNum ${t.downloadNum} reverse ${n}`))}}))}}n=this.peerManager.getPeersOrderByWeight()}if(c++,u++,0===n.length)break}this.loadedPeerNum=a}onBufferManagerLost(e,t,s,i){this.currLostSN=e,s&&(this.nextLostSN=s),this.bitset.delete(e,i),this.bitCounts.delete(e,i)}onBufferManagerSegAdded(e){const{sn:t,segId:s,level:i,size:r}=e;this.notifyAllPeers(t,i,s,r),this.updateLoaded(t,i,s)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[s,i]of this.requestingMap.internalMap){const r=s.split("-"),n=Number(r[1]),a=Number(r[0]);i.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),i.deletePeer(t),this.bitCounts.decre(n,a),t.bitset.delete(n,a))}}updateLoaded(e,t,s){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,s,d.COMPLETE),this.bitCounts.delete(e,t),this.requestingMap.delete(ue(e,t)),this.config.live&&this.checkPeers())}broadcastPlaylist(e,t){if(!this.config.live)return;const s=function(e){const t=e.split("\n");let s=0,i=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){s=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&i++;return s+i-1}(t);if(!this.isMobileNet)for(let i of this.getPeers())i.sendMsgPlaylist(e,t,s);this.playlistInfo.set(e,{seq:s,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:s}=this.playlistInfo.get(e),i=()=>{for(let s of this.getPeers()){const i=s.getLatestPlaylist(e,t);if(i)return this.playlistInfo.set(e,i),this.gotPlaylist=!0,i}return null};let r=i();return!r&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await v(240),this.gotPlaylist=!1,r=i()),r}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:s}=this.engine;if(!t||t.src!==s&&0===t.currentTime){if(this.logger.info("try get video element"),t=oe(this.config.mediaElem,s),!t)return 4;this.engine.media=t}let i=function(e){let t=0,s=e.currentTime,i=e.buffered;for(let e=i.length-1;e>=0;e--)if(s>=i.start(e)&&s<=i.end(e)){t=i.end(e)-s;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return i}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear(),this.engine.removeAllListeners(t.MEDIA_REBUFFER)}clearCache(){"SegmentStore"===this.bufMgr.name?this.engine.emit(t.BM_FATAL_ERROR):this.bufMgr.clear(),this.bitset.clear()}async _handleSynOutput(e,t,s,i,r,n){if(this.logger.info(`syn output ${e} http ${t} p2p ${s} time ${i}`),!this.config.validateSegment(e,new Uint8Array(r)))return!1;if(n){const t=await k(r);if(t&&t!==n)return this.logger.warn(`${e} computedHash ${t} != hash ${n}`),!1}return!0}_handleSynError(e,t,s,i){const{logger:r,config:n}=this;r.warn(`SYN_ERROR ${t}-${s} code ${i}`),i!==rs&&e.hasPartialBuffer&&s>this.loadingSN?r.warn(`syn abort ${s} with partial buffer`):this.requestingMap.delete(ue(s,t)),n.live&&this.checkPeers()}_notifySynthesizer(e,t,s,i,r,n,a=!0){const o=this.requestingMap.get(ue(s,i));o&&this._trySetPeerForSyn(o,e,t,s,i,r,n,a)}_trySetPeerForSyn(e,t,s,i,r,n,a,o=!1){const{logger:l}=this,h=e.segId;if(s&&h&&s!==h)return l.warn(`notifySynthesizer segId ${s} not match ${h}`),!1;if(e.isFull)return!0;if(e.isAlmostDeadline)return!0;if(e.isEmpty){if(e.hasForwardBuffer&&f()){if(e.setReversePeer(t,n))return c(!0,o),!0}else if(e.hasReverseBuffer&&u()&&e.setForwardPeer(t,n))return c(!1,o),!0}else if(!e.hasForwardPeer&&u()){if(e.setForwardPeer(t,n))return c(!1,o),!0}else if(!e.hasReversePeer&&f()&&e.setReversePeer(t,n))return c(!0,o),!0;function c(e,n){n?t.requestDataById(s,i,!0,{level:r,reverse:e}):t.requestDataBySN(i,!1,{level:r,reverse:e})}function u(){return a===d.PARTIAL_FORWARD||a===d.COMPLETE}function f(){return a===d.PARTIAL_REVERSE||a===d.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:s}=this.config;t||s||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,s={level:e};if(t&&!this.config.live){const{currentTime:e}=t;s.pos=Math.round(e)}return s}checkSynthesizer(e,t){const s=ue(e,t),i=this.requestingMap.get(s);i&&(0===i.streamListeners?(this.logger.info(`destroy syn ${s} without listeners`),this.requestingMap.delete(s)):this.logger.info(`keep syn ${s} with listeners`))}setupSynForLoad(e,t,s,i,r){const{forwardPeer:n,reversePeer:a}=this.targetPeers,o=ue(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(i):(l=new ps(this.coordinator,this.logger,e,t,s,this.httpRangeSupported,i),this._setupSynthesizer(l),this.requestingMap.set(o,l)),l.prefetchTimeout&&r<1e3*this.allowP2pLimit&&!n&&!a)return l.setTimeout(0);r>700&&(n&&l.setForwardPeer(n)&&n.requestDataById(s,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(s,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:r,!0)}async disconnectLoadingPeer(e,t){let s=e;if(!s){const e=await this.bufMgr.getSegById(this.loadingSegId);e&&e.fromPeerId&&(s=e.fromPeerId)}let i=!1;return s&&(this.logger.warn(`disconnect loading peer ${s}`),s.split(":").forEach((e=>{if(t&&e===t)return;i=!0;const s=this.peerManager.getPeer(e);s&&s.close(!0)}))),i}}class ys{constructor(t,s,i,r){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=c,this.attachments=r%this.packetSize==0?r/this.packetSize:Math.floor(r/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:i,sn:t,level:s,size:r,reverse:!1},this.sink=(0,a.h)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.h.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,s){this.streamListeners.push({handler:s,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:s}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((i=>i.peerId!==e||(i.handler(t,s,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let s of this.streamListeners){const{handler:i}=s;i(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:s}=this.pieceMsg;for(let i of this.streamListeners){const{handler:r}=i;r(t,s,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const Es=/^age:\s*[\d.]+\s*$/im;function Ss(e,t,s,i){if(!e)return!1;const r=i&&i.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}const Ts=class{constructor(e){this.xhrSetup=e&&e.xhrSetup||null,this.stats=C(),this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.loader=null}destroy(){this.destroyed=!0,this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){if(this.destroyed)return;const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,t.url)})).catch((e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r(s,t.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)})).catch((e=>{this.callbacks.onError({code:s.status,text:e.message},t,s,i)})):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[t]);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,self.clearTimeout(this.requestTimeout),s.timeout=r&&Number.isFinite(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.tfirst=s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,n="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=n||t.response;if(null!=r){s.tload=s.loading.end=Math.max(self.performance.now(),s.loading.first);const n="arraybuffer"===t.responseType?r.byteLength:r.length;if(s.loaded=s.total=n,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(s,e,r,t),!this.callbacks)return;const o={url:t.responseURL,data:r,code:i};return void this.callbacks.onSuccess(o,s,e,t)}}const a=r.loadPolicy.errorRetry;Ss(a,s.retry,!1,{url:e.url,data:void 0,code:i})?this.retry(a):this.callbacks.onError({code:i,text:t.statusText},e,t,s)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Ss(e,this.stats.retry,!0))this.retry(e);else{const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=function(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}(e,s.retry),s.retry++,this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Es.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};const _s=class extends vs{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=P(t.segmentBypass)?t.segmentBypass:()=>!1,!0===t.httpStreamEnabled?this.streamEnabled=ds():this.streamEnabled=!1}async handleGetMediaData(e,s){const{logger:i,engine:r,config:n}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return i.warn(`cannot get frag ${a}`),s.postMessage({action:t.SW_GET_MEDIA});r.currentLevelIndex=l.level;const{sn:h,level:d}=l,c=this.config.segmentId(String(d),h,a,o);if(r.segmentLoadCount++,this.segmentBypass(a,l.tagList))return i.info(`bypass frag ${a}`),s.postMessage({action:t.SW_GET_MEDIA});if(r.segmentLoadCount<n.startFromSegmentOffset)return this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout,!1);const u=c===this.loadingSegId;if(u&&(i.warn(`duplicate request ${c}`),this.prefetchOnly))return s.postMessage({action:t.SW_GET_MEDIA});this.loadingSN=h,r.bufMgr&&(r.bufMgr.loadingSN=h),this.loadingSegId=c;const f=await this.bufMgr.getSegById(c);if(f)return l.loaded=f.size,l.fromPeerId=f.fromPeerId,i.info(`bufMgr found seg sn ${h} segId ${c} size ${l.loaded}`),r.emit(t.FRAG_LOADED,{url:a,sn:h,level:d,segId:c,loaded:l.loaded,duration:l.duration,byP2p:!0,fromPeerId:f.fromPeerId}),this._onFragLoaded(),s.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return i.info(`prefetchOnly, skip p2p load ${c}`),this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),i.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const m=ue(h,d);if(this.resolveMap.has(h)||u){let e=this.requestingMap.get(m);if(e||u){e&&this.httpRangeSupported&&(i.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let r=setTimeout((()=>{i.info(`notify seg ${h} timeout`),r=-1,s.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{r<0||e&&e.level===d&&(clearTimeout(r),i.info(`notify seg ${e.sn}`),s.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else i.warn(`${h} is requesting, fallback`),s.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,d,c,g)){await this._loadFragByP2p(l,s,h,c,a,d,o,p)||(i.warn(`p2p timeout switch to http load ${c}`),this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,s,c,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,s,i,r,n,a,o=!0){const{sn:l,level:c}=e,u=ue(l,c),f=g(r,h,!0),p={},m=this.streamEnabled&&o?new cs(p):new Ts(p);let v={url:f,responseType:"arraybuffer",...b(n)};const y={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},S={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,s.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,s.postMessage({action:t.SW_GET_MEDIA})},onSuccess:async(n,a)=>{this.fragLoading=!1;const{data:o}=n;let h=a.loading.end-a.loading.start;if(this.logger.info(`HTTP loaded ${i} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(i)){const e=E(o).buffer,t=new Q(l,i,e,"",c);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(u),e.segId=i,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:r,sn:l,level:c,segId:i,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),s.postMessage({action:t.SW_GET_MEDIA,data:{url:r,buffer:o}})}};if(this.streamEnabled&&o){let e;S.onBodyStart=t=>{!e&&t>0&&(this.notifyAllPeers(l,c,i,t,d.PARTIAL_FORWARD),e=new ys(l,c,i,t),this.segmentBuilderMap.has(u)||this.segmentBuilderMap.set(u,e))},S.onUpdate=(t,s,r)=>{if(r)return this.logger.warn(`loadFragByHttp ${i} aborted`),void this.segmentBuilderMap.delete(u);e&&e.receiveBytes(t,s)}}m.load(v,y,S)}async _loadFragByP2p(e,s,i,r,n,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${i} segId ${r} level ${a}`);const d=await this.load(i,r,a,n,o,l);if(d&&d.data){const{data:o,fromPeerId:l,size:c}=d;if(h.info(`p2p loaded segId ${r} level ${a} size ${o.byteLength}`),!await this.bufMgr.hasSegOfId(r)){const e=new Q(i,r,o,l,a,d.ext);h.info(`bufMgr putSeg ${i} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:n,sn:i,level:a,segId:r,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),s.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:o,size:c}}),!0}h.warn(`P2P timeout load segId ${r}`);const c=await this.bufMgr.getSegById(r);return!!c&&(this.fragLoading=!1,h.info(`already loaded seg sn ${i} segId ${r}`),s.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:c.data}}),!0)}notifySWMessage(e,s,i){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(s,i);else this.logger.warn(`unknown action ${e}`)}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(){if(!this.engine)return;const{media:e,targetDuration:t}=this.engine;!this.config.live&&e&&t&&(this.currPlaySN=Math.ceil(e.currentTime/t))}load(e,t,s,i,r,n){const{logger:a,config:o}=this;let l={...b(r),proxied:!0,url:i,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,s,t,l,n);const h=new Promise((i=>{const r={resolve:i,sn:e,level:s,segId:t};this.resolveMap.set(e,r)}));return this.targetPeers={},h}isCritical(){return this.resolveMap.has(this.loadingSN)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,s)=>{const{config:i,logger:r}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:d,time:c,http:u,p2p:f}=s,g=this.resolveMap.has(a);g&&(this.fragLoading=!1);const p=await this._handleSynOutput(n,u,f,c,o,h.hash),m=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(u,f,d),g){r.info(`receive criticalSeg seg_id ${n}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:f>0?m:void 0,ext:h})}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else{if(r.error(`segment ${n} validate failed`),g){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(ue(a,l)),this.disconnectLoadingPeer(m)}})).on(t.SYN_ERROR,((t,s)=>{const{sn:i,level:r}=t;if(this.resolveMap.has(i)){const e=this.resolveMap.get(i);this.resolveMap.delete(i),e.resolve()}this._handleSynError(e,r,i,s)}))}_handleDCHave(e,t,s,i,r,n){this._notifySynthesizer(e,i,t,s,r,n,this.resolveMap.has(t)),this.config.live&&j((()=>{this.checkPeers()}))}},Ls="2.13.0";class bs extends kt{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},s=null){super(e,s),this.swSupported=self.isSecureContext,this.levels=[],this.bypassLevels=[],this.currentLevelIndex=0,this.currentSrc="",this.swVersion="",this.media=oe(this.config.mediaElem),this.workerKeepAliveInterval=null,this.fragMap=new Map,this.engineName=bs.name,bs.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),s&&(s.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),s.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:i,signalId:r,browserInfo:n}=this.setup();if(this.onLevelLoaded=e=>{const{config:s}=this,a=e.live;s.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...n,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${i(this.currentSrc)}|${r}[${te.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${ne.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(s.startSN=e.startSN,s.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},0===this.config.httpLoadTime&&(this.config.live?this.on(t.LEVEL_LOADED,(e=>{const{fragments:t,averagetargetduration:s,startSN:i}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,s,i)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,s)=>{this.multiBitrate=e.length>1,this.currentSrc=s,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{this.curTsUri=e;const{config:t}=this;!this.rangeTested&&t.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,t.logger&&t.logger.info(JSON.stringify({engine:this.engineName,...this.browserInfo}))),this.segmentLoadCount>=t.startFromSegmentOffset&&this.resumeTracker()},this.on(t.FRAG_LOADED,this.onFragLoaded),this.swSupported){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:s,data:i}=e.data;if(!s)return;if(s===t.SW_DEBUG){const{level:e,text:t}=i;return void(this.logger&&this.logger[e](`hls-proxy ${this.swVersion}: ${t}`))}const r=e.ports[0];if(r){if(this.logger&&this.logger.info(`engine onmessage action ${s}`),r.postMessage({action:s,pong:!0}),!this.p2pEnabled||!i)return r.postMessage({action:s});if(s===t.SW_GET_PLAYLIST)this.handleGetPlaylist(i,r);else{if(!this.scheduler)return r.postMessage({action:s});this.scheduler.notifySWMessage(s,i,r)}}else this.logger&&this.logger.error(`sender not found in action ${s}`)}}this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let s=null;const i=()=>{s||(s=setTimeout((()=>{t()}),2500))},r=()=>{null!=s&&(clearTimeout(s),s=null)};return e.addEventListener("waiting",i),e.addEventListener("playing",r),()=>{e.removeEventListener("waiting",i),e.removeEventListener("playing",r)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,s,i=!1){const{config:r,logger:n}=this,{url:a,redirectedUrl:o,text:l,ver:d}=e;return this.swVersion=d,-1===function(e,t){for(var s=e.split("."),i=t.split("."),r=0;r<Math.max(s.length,i.length);r++){var n=parseInt(s[r]||0),a=parseInt(i[r]||0);if(n<a)return-1;if(n>a)return 1}return 0}(d,Ls)?(console.warn(`hls-proxy.js version should >= ${Ls}`),s.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(R(a))>=0?(console.warn("bypass audio track"),n&&n.warn("bypass audio track"),s.postMessage({action:t.SW_GET_PLAYLIST})):(s.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:n&&n.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,R(a),o,i),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!r.live&&t()){const s=new URL(e.scope);this.pathname=s.pathname+h;const i=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;n&&(n.error(t),n.report(t,"SWKeepAlive",this.peerId,"2.17.12"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,s)=>{fetch(`${e}/keepalive/`).then((e=>{if(e.ok)return e.text();throw new Error("keepalive failed")})).then((e=>{if(""!==e.trim())throw new Error("not valid keepalive response");t()})).catch((e=>{s(e)}))}))).catch((e=>{i(e)})):i("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,s,i,r=!1){const n=s;i&&(s=i);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const o=jt.parseLevelPlaylist(e,s);this.levels.length>0?(i=this.levels.indexOf(R(o.url)),-1===i?(this.restartP2p(),this.currentSrc=n,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&n!==this.currentSrc&&this.restartP2p(),this.currentSrc=n,this.levels=[R(s)]),this.emit(t.LEVEL_LOADED,o),a.live&&T(this.fragMap,200),o.fragments.forEach((e=>{e.level=i;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const s=e.byteRange;2===s.length&&(t=`${t}|bytes=${s[0]}-${s[1]-1}`),this.fragMap.set(t,e)})),!r&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(R(s),e)}else{const i=jt.parseMasterPlaylist(e,s);""!==this.currentSrc&&this.restartP2p(),i.length>0&&(i.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=i.map((e=>R(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{jt.parseMasterPlaylistMedia(e,s,t).forEach((e=>{e.url&&this.bypassLevels.push(R(e.url))}))}))),this.emit(t.MANIFEST_PARSED,i,n)}this._setupSegmentId()}async handleGetPlaylist(e,s){const{config:i,logger:r,scheduler:n}=this,{url:a}=e,o=R(a);if(n&&n.playlistInfo.has(o)){const t=await n.getPlaylistFromPeer(o);if(t&&t.data){const{data:i,seq:n}=t;return r&&r.info(`got playlist from peer seq ${n}`),void this.handlePlaylist({text:i,...e},s,!0)}}try{const{text:i,redirectedUrl:n}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(i))return r&&r.warn(`not m3u8: ${i}`),s.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:i,redirectedUrl:n,...e},s)}catch(e){s.postMessage({action:t.SW_GET_PLAYLIST})}}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return S||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}return this.media=oe(t.mediaElem),this.media||e&&e.warn("no video element found"),ks.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,s)=>{const{serviceWorker:i}=navigator;i||s(e),i.getRegistration().then((i=>{i?i.unregister().then(t).catch(s):s(e)}))}))}async _init(e,t){const{logger:s,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.mediaTimer=setInterval((()=>{const e=()=>this.hlsjs&&this.hlsjs.media;if(this.media){const t=e();t&&this.media!==t&&(this.media=t),clearInterval(this.mediaTimer),this.rubufferTimer=setTimeout((()=>{this.watchRebuffering(this.media)}),15e3)}else this.media=e()||oe(i.mediaElem)}),3e3);let r=new _s(this,i);r.fragMap=this.fragMap;try{await super._init(e,r,t)}catch(e){return void(s&&s.error(e))}r.server=this.fetcher,this.scheduler=r}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.on(t.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"),clearInterval(this.mediaTimer),clearTimeout(this.rubufferTimer),this.offEventRebuffer&&this.offEventRebuffer(),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&this.tracker instanceof Ct&&(this.tracker.stopP2P(),this.tracker=null,this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED),this.removeAllListeners(t.FRAG_LOADED),clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null}destroy(){this.swSupported&&(navigator.serviceWorker.onmessage=void 0),super.destroy()}async _loadPlaylistByHttp(e){const t=g(e,h,!0),s=await fetch(t);return{text:await s.text(),redirectedUrl:s.redirected?s.url:void 0}}}const Rs=bs;function As(e,t,s="main"){return"main"!==s}function Ps(e,t,s){let i,r,n;const a=performance.now();n=a,r=s?n-s.getMeanTimeToLoaded(t):a-200,i=r-100,e.trequest=i,e.tfirst=r,e.tload=n,e.loading={first:i,start:r,end:n},e.loaded=t,e.total=t}const ws=class extends vs{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitingPeers=0,this.waitingSeg={},this.requestedSet=new Set}updatePlaySN(e){this.currPlaySN=e}load(e,t,s){const{logger:i,config:r}=this;this.context=e;const{rangeStart:n,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:d,level:c}=l;this.callbacks=s,this.criticalSeg={sn:d,level:c,segId:h};let u=e.defaultTimeout-1e3*r.httpLoadTime;const f={rangeStart:Number(n),rangeEnd:Number(a),url:o,httpLoadTime:1e3*r.httpLoadTime,xhrSetup:r.xhrSetup,segId:h,headers:Object.keys(e.headers||{}).length>0?e.headers:void 0};this.setupSynForLoad(d,c,h,f,u),this.targetPeers={}}isCritical(){return!(!this.criticalSeg||this.criticalSeg.segId!==this.loadingSegId)}addPeer(e){super.addPeer(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,s)=>{const{config:i,logger:r}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:d,time:c,http:u,p2p:f}=s,g=this.criticalSeg&&this.criticalSeg.segId===n,p=await this._handleSynOutput(n,u,f,c,o,h.hash),m=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(u,f,d),g&&this.callbacks){r.info(`receive criticalSeg seg_id ${n}`),this.criticalSeg=null;const{frag:e}=this.context;f>0&&(e.fromPeerId=m,e.loadByP2P=!0),this.callbacks.onSuccess({data:o,url:this.context.url},{},{...this.context,ext:h}),this.callbacks=void 0}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else r.error(`segment ${n} validate failed`),g&&this.callbacks.onTimeout({},this.context,null),this.requestingMap.delete(ue(a,l)),this.disconnectLoadingPeer(m)})).on(t.SYN_ERROR,((t,s)=>{const{sn:i,level:r}=t;this.criticalSeg&&this.criticalSeg.sn===i&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,r,i,s)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:s,segId:i})=>{this.criticalSeg&&this.criticalSeg.segId===i&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:s},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:s,level:i})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,s&&this.checkSynthesizer(e,i)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:s,level:i})=>{this.fragLoading=!1,s||this.checkSynthesizer(e,i)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,s,i,r,n){this._notifySynthesizer(e,i,t,s,r,n,this.criticalSeg&&this.criticalSeg.segId===i),this.config.live&&j((()=>{this.checkPeers()}))}};class Is extends kt{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){if(super(t,e),!e)throw new TypeError("hlsjs instance is null");"serviceWorker"in navigator&&this._setupSW(),this.config.xhrSetup=e.config.xhrSetup,this.engineName=Is.name,this._onFragLoading=this._onFragLoading.bind(this),this._onFragLoaded=this._onFragLoaded.bind(this),this._onFragChanged=this._onFragChanged.bind(this),this._onHlsError=this._onHlsError.bind(this),this._onLevelUpdated=this._onLevelUpdated.bind(this);const{channelIdMaker:s,signalId:i,browserInfo:r}=this.setup();if(P(t.interceptSegment)){class e extends this.hlsjs.constructor.DefaultConfig.loader{load(e,s,i){const{url:r}=e;if(e.frag){const e=i.onSuccess;i.onSuccess=(s,i,n,a)=>{s.data=t.interceptSegment(s.data,r),e(s,i,n,a)}}super.load(e,s,i)}}this.hlsjs.config.fLoader=e}const n=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;this._startEngine(this.hlsjs.url,h,r,s,i,l),e.off(this.HLSEvents.LEVEL_LOADED,n)};this._updateHlsEventsHandlers(),e.on(this.HLSEvents.LEVEL_LOADED,n);const a=(e,t)=>{if(!t)return;const{config:s}=this,{fragments:i,averagetargetduration:r,startSN:n}=t.details;s.httpLoadTime=this.determineHttpLoadTime(i,r,n)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,s)=>{this._setupSegmentId();const i=s.levels.length;this.multiBitrate=i>1,e.off(this.HLSEvents.MANIFEST_PARSED,o)};e.on(this.HLSEvents.MANIFEST_PARSED,o),e.on(this.HLSEvents.DESTROYING,(()=>{e.off(this.HLSEvents.LEVEL_LOADED,a),this.destroy()}))}_startEngine(e,t,s,i,r,n={}){const{config:a}=this;a.live=t,this.browserInfo={...s,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${i(e)}|${r}[${te.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=n.startSN,a.endSN=n.endSN,o.info(`startSN ${n.startSN} endSN ${n.endSN}`)),this._init(this.channel,this.browserInfo)}async _init(e,t){const{logger:s,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const r=new ws(this,i);try{await super._init(e,r,t)}catch(e){return void s.error(e)}this.hlsjs.config.fLoader=function(e,t,s,i){const r=i.httpStreamEnabled&&ds();return class extends(n()){constructor(n){super(),this.logger=s,this.isHlsV0=i.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=r||this.isHlsV0?new cs(n):new Ts(n),this.originalLoader=n.loader,this.p2pEnabled=i.p2pEnabled,this.isLive=i.live,this.scheduler=e,this.fetcher=t,this.segmentId=i.segmentId,this.blockTypes=i.p2pBlackList,this.stats=this.httpLoader.stats||C(),this.segmentBypass=P(i.segmentBypass)?i.segmentBypass:()=>!1,this.prefetchOnly=i.prefetchOnly,this.startFromSegmentOffset=i.startFromSegmentOffset,this.interceptSegment=P(i.interceptSegment)?i.interceptSegment:e=>e}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,s){const{logger:i,scheduler:r}=this,{url:n,frag:a}=e;this.isHlsV0||(a.stats=this.stats);const{level:o,sn:l,type:h,tagList:d}=a;let c=a.segId;if(!c){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),c=a.segId=this.segmentId(String(o),l,n,t)}const u=()=>(a.loadByHTTP=!0,new this.originalLoader(t).load(e,t,s));if(!n||!Number.isInteger(l)||As(0,this.blockTypes,h)||this.segmentBypass(n,d))return i.info(`HTTP load blockType ${n}`),u();if(this.fetcher.increMediaRequests(),this.isLive&&r.requestedSet.has(c))return i.warn(`HTTP load duplicated ${n}`),u();if(r.engine.segmentLoadCount<this.startFromSegmentOffset)return u();t.maxRetry=2;const f=r.getBufferedDuration(),g=await this.bufMgr.getSegById(c);if(this.p2pEnabled&&g){i.info(`bufMgr found seg sn ${l} segId ${c} level ${o} size ${g.size}`);let t=E(g.data).buffer,h={url:e.url,data:t};return Ps(this.stats,g.size,r.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void j((()=>{!this.isHlsV0&&s.onProgress&&s.onProgress(this.stats,e,h.data),h.data=this.interceptSegment(h.data,n),s.onSuccess(h,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&r.hasAndSetTargetPeer(l,o,c,f)?this.loadFragByP2p(e,t,s,c,f):(i.info(`fragLoader load ${c} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,s,c))}loadFragByHttp(e,t,s,i){const{logger:n,scheduler:a}=this,{segmentBuilderMap:o}=a,l=e.frag,{sn:h,level:c}=l,u=ue(h,c);if(r){let e;s.onUpdate=(t,s,r)=>{if(r)return n.warn(`loadFragByHttp ${i} aborted`),void o.delete(u);e&&e.receiveBytes(t,s)},s.onBodyStart=t=>{!e&&t>0&&(e=new ys(h,c,i,t),o.has(u)||o.set(u,e),a.notifyAllPeers(h,c,i,t,d.PARTIAL_FORWARD))}}const f=s.onSuccess;s.onSuccess=async(e,t,s)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:r}=e;let d=t.tload-t.trequest;if(n.info(`HTTP loaded ${i} time ${d} speed ${t.total/d}`),l.loaded=t.total,!await this.bufMgr.hasSegOfId(i)){const e=E(r).buffer,t=new Q(h,i,e,this.fetcher.peerId,c);await this.bufMgr.putSeg(t)}o.delete(u),this.fetcher.reportFlow(t.total),e.data=this.interceptSegment(e.data,s.url),f(e,t,s)},e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,s)}loadFragByP2p(t,s,i,r,n){const{logger:a}=this,o=t.frag;let l;l=s.loadPolicy?s.loadPolicy.maxTimeToFirstByteMs:s.timeout,(!l||l>1e3*n)&&(l=1e3*n),t.defaultTimeout=l,this.scheduler.load(t,s,i);const h=i.onSuccess,d=i.onTimeout;i.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),i.onSuccess=h,this.loadFragByHttp(t,s,i,r),i.onTimeout=d},i.onSuccess=async(t,s,n)=>{const{data:l}=t;if(Ps(s=this.stats,l.byteLength,e.coordinator),!await this.bufMgr.hasSegOfId(r)){const e=E(l).buffer,t=new Q(o.sn,r,e,o.fromPeerId||this.fetcher.peerId,o.level,n.ext);await this.bufMgr.putSeg(t)}o.loadByP2P||this.fetcher.reportFlow(s.total),o.loaded=s.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${r}`),!this.isHlsV0&&i.onProgress&&i.onProgress(s,n,l),t.data=this.interceptSegment(t.data,n.url),h(t,s,n)}}}}(r,this.fetcher,s,i),i.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,s){return class extends(n()){constructor(i){super(),this.logger=t,this.xhrLoader=new i.loader(i),this.p2pEnabled=s.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||C()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,s){const{logger:i}=this,{url:r}=e,n=R(r),a=s.onSuccess;if(s.onSuccess=(e,t,s)=>{this.scheduler&&!s.loadedByPeer&&this.scheduler.broadcastPlaylist(n,e.data),a(e,t,s)},this.scheduler&&this.scheduler.playlistInfo.has(n)){const t=await this.scheduler.getPlaylistFromPeer(n);if(t&&t.data){const{data:n,seq:a}=t;i.info(`got playlist from peer seq ${a}`),Ps(this.stats,n.length);let o={url:r,data:n};return e.loadedByPeer=!0,void j((()=>{s.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,s)}}}(r,s,i))}_onFragLoading(e,s){const i=s.frag;let{sn:r,level:n,segId:a}=i;if(!As(i.url,this.config.p2pBlackList,i.type)&&Number.isInteger(r)){if(this.logger&&this.logger.info("loading frag "+r),this.bufMgr&&(this.bufMgr.loadingSN=r),!a){let e;i._byteRange&&(e="bytes="+i._byteRange[0]+"-"+i._byteRange[1]);let t=i.url;this._setupSegmentId(),a=i.segId=this.config.segmentId(String(n),i.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:r,segId:a,byHttp:i.loadByHTTP,level:n})}}_onLevelUpdated(e,t){const{details:s}=t,{hlsjs:i,config:r}=this,{targetduration:n,live:a,fragments:o}=s,l=o.length;if(a&&i&&"main"===o[0].type&&!(l<=4)&&(r.isHlsV0||!i.userConfig.liveSyncDuration&&!i.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;i.config.liveSyncDurationCount!==e&&(i.config.liveSyncDurationCount=e)}}_onFragLoaded(e,s){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:i}=s;this.curTsUri=i.url;const{sn:r,segId:n,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:d,url:c}=i,{config:u,logger:f}=this;this.tracker&&this.tracker.scheduler&&(_(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(n)),As(i.url,u.p2pBlackList,i.type)||(this.bufMgr&&this.bufMgr.loadingSN>=0&&this.emit(t.FRAG_LOADED,{url:c,sn:r,level:l,segId:n,loaded:a,duration:o,byP2p:!!d,fromPeerId:h}),!this.rangeTested&&u.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,f&&f.info(JSON.stringify({engine:this.engineName,hlsjs:this.hlsjsVersion,...this.browserInfo})))),this.segmentLoadCount>=u.startFromSegmentOffset&&this.resumeTracker()}_onFragChanged(e,s){const{frag:i}=s;if(!As(i.url,this.config.p2pBlackList,i.type)){this.logger&&this.logger.info("frag changed: "+i.sn);const{sn:e,duration:s}=i;this.emit(t.FRAG_CHANGED,{sn:e,duration:s})}}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.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}_updateHlsEventsHandlers(e=!1){const t=this.hlsjs;if(!t)return;const s=e?"off":"on";t[s](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[s](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[s](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[s](this.HLSEvents.ERROR,this._onHlsError),t[s](this.HLSEvents.LEVEL_UPDATED,this._onLevelUpdated)}destroy(){this._updateHlsEventsHandlers(!0),super.destroy()}_setupSW(){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:t}=e.data,s=e.ports[0];if(s)return s.postMessage({action:t,pong:!0}),s.postMessage({action:t,data:{bypass:!0}})}}}const Ds=Is;class Cs{static get Events(){return t}static get TrackerZone(){return ne.TrackerZone}static isSupported(){return ne.isSupported()&&(ae()||Rs.isServiceWorkerSupported())}static isServiceWorkerSupported(){return Rs.isServiceWorkerSupported()}static isMSESupported(){return ae()}static getBrowser(){return Z().getBrowser()}static get ServiceWorkerEngine(){return Rs}static get HlsjsEngine(){return Ds}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return Cs.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:s}={}){const{serviceWorker:i}=navigator;return!i||s?Promise.resolve():i.getRegistration().then((s=>s||Promise.race([i.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,s)=>{const i=e.installing||e.waiting||e.active,r=()=>"activated"===i.state&&(i.removeEventListener("statechange",r),t(e),!0);r()||i.addEventListener("statechange",r)}))}(e))).catch((()=>{Promise.resolve()})),v(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const s=()=>{this._realEngine=new Ds(t,e)},i=()=>{this._realEngine=new Rs(e,t)};"1"!==f("_sw")?e.proxyFirst&&t?Rs.isServiceWorkerSupported()?i():s():!e.proxyOnly&&ae()&&t?s():i():i()}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(){return this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}async registerServiceWorker(){return P(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return P(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return ne.version}}Cs.version=ne.version,Cs.protocolVersion=te.VERSION,"object"==typeof self&&(self.P2PEngineHls=Cs);const ks=Cs,Ms=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},xs=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=Os},Os=Number.MAX_SAFE_INTEGER||9007199254740991;let Fs=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Ns=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",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.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),$s=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var Bs="manifest",Us="level",Gs="audioTrack",Hs="subtitleTrack",Vs="main",Ws="audio",qs="subtitle";class js{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Ks{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new js(e),this.fast_=new js(t),this.defaultTTFB_=i,this.ttfb_=new js(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new js(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new js(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new js(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const s=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function zs(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function Ys(){return Ys=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},Ys.apply(null,arguments)}function Xs(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,i)}return s}function Qs(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Xs(Object(s),!0).forEach((function(t){zs(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Xs(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}class Js{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Zs,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Zs=function(){},ei={trace:Zs,debug:Zs,log:Zs,warn:Zs,info:Zs,error:Zs};function ti(){return Ys({},ei)}function si(e,t,s){return t[e]?t[e].bind(t):function(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Zs}(e,s)}const ii=ti();const ri=ii;function ni(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ai,oi;var li=oi?ai:(oi=1,ai={}),hi=ni(li);function di(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ci(e,t=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(e);if(t){const e=s.indexOf("\0");return-1!==e?s.substring(0,e):s}return s.replace(/\0/g,"")}const s=e.length;let i,r,n,a="",o=0;for(;o<s;){if(i=e[o++],0===i&&t)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|63&n)}}return a}function ui(e){let t="";for(let s=0;s<e.length;s++){let i=e[s].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function fi(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var gi,pi={exports:{}};var mi=(gi||(gi=1,function(e,t){!function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=a.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=a.normalizePath(r.path),a.buildURLFromParts(r)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(c)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=s.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=s.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()}(pi)),pi.exports);class vi{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var yi="audio",Ei="video",Si="audiovideo";class Ti{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const s=Ri(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;i=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[yi]:null,[Ei]:null,[Si]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new vi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=mi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[yi]=null,e[Ei]=null,e[Si]=null}}function _i(e){return"initSegment"!==e.sn}class Li extends Ti{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(Ms(e)&&Ms(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const s=this._decryptdata=t[e[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=Ms(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),s=e.length;if(s>1||1===s&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){Ms(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return _i(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class bi extends Ti{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function Ri(e,t){const s=Object.getPrototypeOf(e);if(s){const e=Object.getOwnPropertyDescriptor(s,t);return e||Ri(s,t)}}const Ai=Math.pow(2,32)-1,Pi=[].push,wi={video:1,audio:2,id3:3,text:4};function Ii(e){return String.fromCharCode.apply(null,e)}function Di(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function Ci(e,t){const s=Mi(e,t);return s<0?4294967296+s:s}function ki(e,t){let s=Ci(e,t);return s*=Math.pow(2,32),s+=Ci(e,t+4),s}function Mi(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function xi(e,t){const s=[];if(!t.length)return s;const i=e.byteLength;for(let r=0;r<i;){const n=Ci(e,r),a=n>1?r+n:i;if(Ii(e.subarray(r+4,r+8))===t[0])if(1===t.length)s.push(e.subarray(r+8,a));else{const i=xi(e.subarray(r+8,a),t.slice(1));i.length&&Pi.apply(s,i)}r=a}return s}function Oi(e){const t=[],s=e[0];let i=8;const r=Ci(e,i);i+=4;let n=0,a=0;0===s?(n=Ci(e,i),a=Ci(e,i+4),i+=8):(n=ki(e,i),a=ki(e,i+8),i+=16),i+=2;let o=e.length+a;const l=Di(e,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=Ci(e,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return ri.warn("SIDX has hierarchical references (not supported)"),null;const l=Ci(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:t}}function Fi(e){const t=[],s=xi(e,["moov","trak"]);for(let e=0;e<s.length;e++){const i=s[e],r=xi(i,["tkhd"])[0];if(r){let e=r[0];const s=Ci(r,0===e?12:20),n=xi(i,["mdia","mdhd"])[0];if(n){e=n[0];const r=Ci(n,0===e?12:20),a=xi(i,["mdia","hdlr"])[0];if(a){const e=Ii(a.subarray(8,12)),n={soun:yi,vide:Ei}[e],o=Ni(xi(i,["mdia","minf","stbl","stsd"])[0]);n?(t[s]={timescale:r,type:n,stsd:o},t[n]=Qs({timescale:r,id:s},o)):t[s]={timescale:r,type:e,stsd:o}}}}}return xi(e,["moov","mvex","trex"]).forEach((e=>{const s=Ci(e,4),i=t[s];i&&(i.default={duration:Ci(e,12),flags:Ci(e,20)})})),t}function Ni(e){const t=e.subarray(8),s=t.subarray(86),i=Ii(t.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const e=xi(t,[i])[0];xi(e.subarray("enca"===i?28:78),["sinf"]).forEach((e=>{const t=xi(e,["schm"])[0];if(t){const s=Ii(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=xi(e,["frma"])[0];t&&(n=Ii(t))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=xi(s,["avcC"])[0];e&&e.length>3&&(n+="."+Ui(e[1])+Ui(e[2])+Ui(e[3]),r=$i("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const e=xi(t,[i])[0],s=xi(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=Bi(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=Bi(s,e);const i=s[e++];if(64!==i)break;if(n+="."+Ui(i),e+=12,5!==s[e++])break;e=Bi(s,e);const r=s[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=xi(s,["hvcC"])[0];if(e&&e.length>12){const t=e[1],s=["","A","B","C"][t>>6],i=31&t,r=Ci(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+s+i,n+="."+function(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];if(t||h){h="."+t.toString(16).toUpperCase()+h}}n+=h}r=$i("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=$i(n,s)||n;break;case"vp09":{const e=xi(s,["vpcC"])[0];if(e&&e.length>6){const t=e[4],s=e[5],i=e[6]>>4&15;n+="."+Gi(t)+"."+Gi(s)+"."+Gi(i)}break}case"av01":{const e=xi(s,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,i=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,d=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,p=1,m=1,v=0;n+="."+t+"."+Gi(i)+a+"."+Gi(h)+"."+d+"."+c+u+f+"."+Gi(g)+"."+Gi(p)+"."+Gi(m)+"."+v,r=$i("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function $i(e,t){const s=xi(t,["dvvC"]),i=s.length?s[0]:xi(t,["dvcC"])[0];if(i){const t=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return e+"."+Gi(t)+"."+Gi(s)}}function Bi(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function Ui(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Gi(e){return(e<10?"0":"")+e}function Hi(e,t){xi(e,["moov","trak"]).forEach((e=>{const s=xi(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=xi(i,["enca"]);const n=r.length>0;n||(r=xi(i,["encv"])),r.forEach((e=>{xi(n?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const s=function(e){const t=xi(e,["schm"])[0];if(t){const s=Ii(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=xi(e,["schi","tenc"])[0];if(t)return t}}}(e);s&&t(s,n)}))}))}))}function Vi(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function Wi(e,t){const s=[],i=t.samples,r=t.timescale,n=t.id;let a=!1;return xi(i,["moof"]).map((o=>{const l=o.byteOffset-8;xi(o,["traf"]).map((o=>{const h=xi(o,["tfdt"]).map((e=>{const t=e[0];let s=Ci(e,4);return 1===t&&(s*=Math.pow(2,32),s+=Ci(e,8)),s/r}))[0];return void 0!==h&&(e=h),xi(o,["tfhd"]).map((h=>{const d=Ci(h,4),c=16777215&Ci(h,0);let u=0;const f=!!(16&c);let g=0;const p=!!(32&c);let m=8;d===n&&(!!(1&c)&&(m+=8),!!(2&c)&&(m+=4),!!(8&c)&&(u=Ci(h,m),m+=4),f&&(g=Ci(h,m),m+=4),p&&(m+=4),"video"===t.type&&(a=qi(t.codec)),xi(o,["trun"]).map((n=>{const o=n[0],h=16777215&Ci(n,0),d=!!(1&h);let c=0;const f=!!(4&h),p=!!(256&h);let m=0;const v=!!(512&h);let y=0;const E=!!(1024&h),S=!!(2048&h);let T=0;const _=Ci(n,4);let L=8;d&&(c=Ci(n,L),L+=4),f&&(L+=4);let b=c+l;for(let l=0;l<_;l++){if(p?(m=Ci(n,L),L+=4):m=u,v?(y=Ci(n,L),L+=4):y=g,E&&(L+=4),S&&(T=0===o?Ci(n,L):Mi(n,L),L+=4),t.type===Ei){let t=0;for(;t<y;){const n=Ci(i,b);if(b+=4,ji(a,i[b])){Ki(i.subarray(b,b+n),a?2:1,e+T/r,s)}b+=n,t+=n+4}}e+=m/r}})))}))}))})),s}function qi(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function ji(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Ki(e,t,s,i){const r=zi(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){ri.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=Di(r,t);if(t+=2,49===e){const e=Ci(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=r[t++]}i.push({type:e,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let s=0;s<16;s++){const i=r[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];i.push({payloadType:a,pts:s,uuid:e.join(""),userData:ci(l),userDataBytes:l})}}}function zi(e){const t=e.byteLength,s=[];let i=1;for(;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return e;const r=t-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=e[a];return n}const Yi=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Xi={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Qi(e,t){const s=Xi[t];return!!s&&!!s[e.slice(0,4)]}function Ji(e,t,s=!0){return!e.split(",").some((e=>!Zi(e,t,s)))}function Zi(e,t,s=!0){var i;const r=di(s);return null!=(i=null==r?void 0:r.isTypeSupported(er(e,t)))&&i}function er(e,t){return`${t}/mp4;codecs=${e}`}function tr(e){if(e){const t=e.substring(0,4);return Xi.video[t]}return 2}function sr(e){const t=Yi();return e.split(",").reduce(((e,s)=>{const i=t&&qi(s)?9:Xi.video[s];return i?(2*i+e)/(e?3:2):(Xi.audio[s]+e)/(e?2:1)}),0)}const ir={};const rr=/flac|opus|mp4a\.40\.34/i;function nr(e,t=!0){return e.replace(rr,(e=>function(e,t=!0){if(ir[e])return ir[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<s.length;r++){var i;if(Zi(s[r],"audio",t))return ir[e]=s[r],s[r];if("mp3"===s[r]&&null!=(i=di(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)))}function ar(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(or(e,"audio")||or(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function or(e,t){return Qi(e,t)&&Zi(e,t)}function lr(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function hr(e){const t=di(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function dr(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const cr=["NONE","TYPE-0","TYPE-1",null];const ur=["SDR","PQ","HLG"];var fr="",gr="YES",pr="v2";function mr(e){const{canSkipUntil:t,canSkipDateRanges:s,age:i}=e;return t&&i<t/2?s?pr:gr:fr}class vr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class yr{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=null==(t=e.supplemental)?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Er(this._audioGroups,e)}hasSubtitleGroup(e){return Er(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Er(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Sr(e,t){let s=!1,i=[];if(e&&(s="SDR"!==e,i=[e]),t){i=t.allowedVideoRanges||ur.slice(0);const e="SDR"!==i.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const Tr=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(s,i)=>{if(e&&(i=e(s,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}})(t));function _r(e,t){ri.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Lr(e){return e.reduce(((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function br(e,t){var s;return!!e&&e!==(null==(s=t.loadLevelObj)?void 0:s.uri)}const Rr=function(e,t){let s=0,i=e.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=e[r];const a=t(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function Ar(e,t,s=0,i=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const i=e.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Pr(s,i,n)||function(e,t,s){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),s);return e.start<=i}return!1}(n,e,Math.min(r,i))))return n;const a=Rr(t,Pr.bind(null,s,i));return!a||a===e&&n?n:a}function Pr(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=e?1:s.start-i>e&&s.start?-1:0}function wr(e,t,s){const i=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>e}function Ir(e){switch(e.details){case Ns.FRAG_LOAD_TIMEOUT:case Ns.KEY_LOAD_TIMEOUT:case Ns.LEVEL_LOAD_TIMEOUT:case Ns.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Dr(e){return e.details.startsWith("key")}function Cr(e){return Dr(e)&&!!e.frag&&!e.frag.decryptdata}function kr(e,t){const s=Ir(t);return e.default[(s?"timeout":"error")+"Retry"]}function Mr(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function xr(e){return Qs(Qs({},e),{errorRetry:null,timeoutRetry:null})}function Or(e,t,s,i){if(!e)return!1;const r=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return Fr(e)||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}function Fr(e){return 0===e&&!1===navigator.onLine}var Nr=0,$r=2,Br=3,Ur=5,Gr=0,Hr=1,Vr=2,Wr=4;function qr(e){const t={action:Nr,flags:Gr};return e&&(t.resolved=!0),t}const jr=/^(\d+)x(\d+)$/,Kr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class zr{constructor(e,t){"string"==typeof e&&(e=zr.parseAttrList(e,t)),Ys(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}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 s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}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])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce(((e,t)=>(e[t.toLowerCase()]=!0,e)),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=jr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(Kr.lastIndex=0;null!==(s=Kr.exec(e));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o));else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ri.warn(`${e}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function Yr(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Xr{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){ri.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Ys(new zr({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);Ms(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(ri.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ms(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Ms(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class Qr{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some((t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)}))}get hasProgramDateTime(){return!!this.fragments.length&&Ms(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Jr(e,t){return e.length===t.length&&!e.some(((e,s)=>e!==t[s]))}function Zr(e,t){return!e&&!t||!(!e||!t)&&Jr(e,t)}var en=0,tn=1;function sn(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function rn(e){switch(e){case"AES-128":case"AES-256":return en;case"AES-256-CTR":return tn;default:throw new Error(`invalid full segment method ${e}`)}}let nn={};class an{static clearKeyUriToKeyIdMap(){nn={}}static setKeyIdForUri(e,t){nn[e]=t}static addKeyIdForUri(e){const t=Object.keys(nn).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),nn[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!sn(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(fi(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Jr(e.keyFormatVersions,this.keyFormatVersions)&&Zr(e.iv,this.iv)&&Zr(e.keyId,this.keyId)}isSupported(){if(this.method){if(sn(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(sn(this.method)){let t=this.iv;t||("number"!=typeof e&&(ri.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}(e));return new an(this.method,this.uri,"identity",this.keyFormatVersions,t)}return this}}const on=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,ln=/#EXT-X-MEDIA:(.*)/g,hn=/^#EXT(?:INF|-X-TARGETDURATION):/m,dn=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),cn=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class un{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return mi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return hn.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},i=[];if(on.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let r;for(;null!=(r=on.exec(e));)if(r[1]){var n;const e=new zr(r[1],s),a=r[2],o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:un.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),vn(e.CODECS,o);const h=e["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},vn(h,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),s.levels.push(o)}else if(r[3]){const e=r[3],i=r[4];switch(e){case"SESSION-DATA":{const e=new zr(i,s),t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{const e=pn(i,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):ri.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const e=new zr(i,s);s.contentSteering={uri:un.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=mn(i)}}const a=i.length>0&&i.length<s.levels.length;return s.levels=a?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,a={AUDIO:n.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(ln.lastIndex=0;null!==(i=ln.exec(e));){const e=new zr(i[1],s),n=e.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?un.resolve(e.URI,t):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const e=un.findGroup(s,f.groupId)||s[0];yn(f,e,"audioCodec"),yn(f,e,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var a;const o={url:t},l=new Qr(t),h=l.fragments,d=[];let c,u,f,g,p=null,m=0,v=0,y=0,E=0,S=0,T=null,_=new Li(i,o),L=-1,b=!1,R=null;if(dn.lastIndex=0,l.m3u8=e,l.hasVariableRefs=!1,"#EXTM3U"!==(null==(a=dn.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=dn.exec(e));){b&&(b=!1,_=new Li(i,o),_.playlistOffset=y,_.setStart(y),_.sn=m,_.cc=E,S&&(_.bitrate=S),_.level=s,p&&(_.initSegment=p,p.rawProgramDateTime&&(_.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),R&&(_.setByteRange(R),R=null)));const e=c[1];if(e){_.duration=parseFloat(e);const t=(" "+c[2]).slice(1);_.title=t||null,_.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(Ms(_.duration)){_.playlistOffset=y,_.setStart(y),f&&Tn(_,f,l),_.sn=m,_.level=s,_.cc=E,h.push(_);const e=(" "+c[3]).slice(1);_.relurl=e,En(_,T,d),T=_,y+=_.duration,m++,v=0,b=!0}}else{if(c=c[0].match(cn),!c){ri.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),n=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":T?_.setByteRange(r,T):_.setByteRange(r);break;case"PROGRAM-DATE-TIME":_.rawProgramDateTime=r,_.tagList.push(["PROGRAM-DATE-TIME",r]),-1===L&&(L=h.length);break;case"PLAYLIST-TYPE":l.type&&_n(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?_n(l,e,c):h.length>0&&Ln(l,e,c),m=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&_n(l,e,c);const t=new zr(r,l),s=t.decimalInteger("SKIPPED-SEGMENTS");if(Ms(s)){l.skippedSegments+=s;for(let e=s;e--;)h.push(null);m+=s}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&_n(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&_n(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"ENDLIST":l.live||_n(l,e,c),l.live=!1;break;case"#":(r||n)&&_.tagList.push(n?[r,n]:[r]);break;case"DISCONTINUITY":E++,_.tagList.push(["DIS"]);break;case"GAP":_.gap=!0,_.tagList.push([e]);break;case"BITRATE":_.tagList.push([e,r]),S=1e3*parseInt(r),Ms(S)?_.bitrate=S:S=0;break;case"DATERANGE":{const e=new zr(r,l),t=new Xr(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:ri.warn(`Ignoring invalid DATERANGE tag: "${r}"`),_.tagList.push(["EXT-X-DATERANGE",r]);break}case"DISCONTINUITY-SEQUENCE":0!==l.startCC?_n(l,e,c):h.length>0&&Ln(l,e,c),l.startCC=E=parseInt(r);break;case"KEY":{const e=pn(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=Ys({},f)),f[e.keyFormat]=e)}else ri.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}" (light build)`);break}case"START":l.startTimeOffset=mn(r);break;case"MAP":{const e=new zr(r,l);if(_.duration){const t=new Li(i,o);Sn(t,e,s,f),p=t,_.initSegment=p,p.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=p.rawProgramDateTime)}else{const t=_.byteRangeEndOffset;if(t){const e=_.byteRangeStartOffset;R=`${t-e}@${e}`}else R=null;Sn(_,e,s,f),p=_,b=!0}p.cc=E;break}case"SERVER-CONTROL":g&&_n(l,e,c),g=new zr(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&_n(l,e,c);const t=new zr(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,s=v++,i=new zr(r,l),n=new bi(i,_,o,s,t);e.push(n),_.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new zr(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new zr(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:ri.warn(`line parsed but not handled: ${c}`)}}}T&&!T.relurl?(h.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(En(_,T,d),_.cc=E,l.fragmentHint=_,f&&Tn(_,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const A=h.length,P=h[0],w=h[A-1];if(y+=l.skippedSegments*l.targetduration,y>0&&A&&w){l.averagetargetduration=y/A;const e=w.sn;l.endSN="initSegment"!==e?e:0,l.live||(w.endList=!0),L>0&&(!function(e,t){let s=e[t];for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(h,L),P&&d.unshift(P))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&P&&fn(d,l),l.endCC=E,l}}function fn(e,t){let s=e.length;if(!s){if(!t.hasProgramDateTime)return;{const i=t.fragments[t.fragments.length-1];e.push(i),s++}}const i=e[s-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=e[i])?void 0:a.sn)<t.startSN)break;const s=gn(t,h,e,i,r);if(-1!==s){l.tagAnchor=t.fragments[s].ref;break}}}}function gn(e,t,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(t>=o||0===i){var a;if(t<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>s.length){for(let a=(s[i+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function pn(e,t,s){var i,r;const n=new zr(e,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&ri.error(`Invalid IV: ${n.IV}`);const c=o?un.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new an(a,c,d,u,l,n.KEYID)}function mn(e){const t=new zr(e).decimalFloatingPoint("TIME-OFFSET");return Ms(t)?t:null}function vn(e,t){let s=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const i=s.filter((t=>Qi(t,e)));i.length&&(t[`${e}Codec`]=i.map((e=>e.split("/")[0])).join(","),s=s.filter((e=>-1===i.indexOf(e))))})),t.unknownCodecs=s}function yn(e,t,s){const i=t[s];i&&(e[s]=i)}function En(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Sn(e,t,s,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Tn(e,t,s){e.levelkeys=t;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||i.push(e)}function _n(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function Ln(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function bn(e,t){const s=t.startPTS;if(Ms(s)){let i,r=0;t.sn>e.sn?(r=s-e.start,i=e):(r=e.start-s,i=t),i.duration!==r&&i.setDuration(r)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Rn(e,t,s,i,r,n,a){i-s<=0&&(a.warn("Fragment should have a positive duration",t),i=s+t.duration,n=r+t.duration);let o=s,l=i;const h=t.startPTS,d=t.endPTS;if(Ms(h)){const c=Math.abs(h-s);e&&c>e.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${t.level} ${e.url}`):Ms(t.deltaPTS)?t.deltaPTS=Math.max(c,t.deltaPTS):t.deltaPTS=c,o=Math.max(s,h),s=Math.min(s,h),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,l=Math.min(i,d),i=Math.max(i,d),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const c=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(i-t.start),t.startPTS=s,t.maxStartPTS=o,t.startDTS=r,t.endPTS=i,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const g=u-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)bn(p[f],p[f-1]);for(f=g;f<p.length-1;f++)bn(p[f],p[f+1]);return e.fragmentHint&&bn(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function An(e,t,s){if(e===t)return;let i=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){i=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,s){const i=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let h=r;h<=n;h++){const r=l[a+h];let n=o[h];if(i&&!n&&r&&(n=t.fragments[h]=r),r&&n){s(r,n,h,o);const i=r.relurl,a=n.relurl;if(i&&xn(i,a))return void(t.playlistParsingError=Pn(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=Pn(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,((e,s,r,a)=>{if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){const i=e.cc-s.cc;for(let e=r;e<a.length;e++)a[e].cc+=i;t.endCC=a[a.length-1].cc}Ms(e.startPTS)&&Ms(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(n=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,i=e.initSegment)}));const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)})),t.skippedSegments){if(t.deltaUpdateFailed=a.some((e=>!e)),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,s){const{dateRanges:i,recentlyRemovedDateranges:r}=t,n=Ys({},e);r&&r.forEach((e=>{delete n[e]}));const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach((e=>{const t=n[e],r=new Xr(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Tr(i[e].attr)}"`)})),n}(e.dateRanges,t,s));const i=e.fragments.filter((e=>e.rawProgramDateTime));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&En(o[e],o[e-1],i);fn(i,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const s=Dn(e,t.startSN-1);t.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}!function(e,t,s){if(e&&t){let i=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),n?Rn(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):wn(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function Pn(e,t,s,i,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function wn(e,t,s=!0){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&s)a=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}!function(e,t){if(t){const s=e.fragments;for(let i=e.skippedSegments;i<s.length;i++)s[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,a)}function In(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const i=e.fragments,r=4;if(i.length&&s*r>t){const e=1e3*i[i.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function Dn(e,t,s){if(!e)return null;let i=e.fragments[t-e.startSN];return i||(i=e.fragmentHint,i&&i.sn===t?i:t<e.startSN&&s&&s.sn===t?s:null)}function Cn(e,t,s){return e?kn(e.partList,t,s):null}function kn(e,t,s){if(e)for(let i=e.length;i--;){const r=e[i];if(r.index===s&&r.fragment.sn===t)return r}return null}function Mn(e){e.forEach(((e,t)=>{var s;null==(s=e.details)||s.fragments.forEach((e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function xn(e,t){return!(e===t||!t)&&On(e)!==On(t)}function On(e){return e.replace(/\?[^?]*$/,"")}class Fn extends Js{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=null==t?void 0:t.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=s;break}a===e.substring(0,a.length)&&(r=s)}if(-1!==r){const e=i[r],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&mr(s);return new vr(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const e=Math.max(o||0,0);i.appliedTimelineOffset=e,i.fragments.forEach((t=>{t.setStart(t.playlistOffset+e)}))}if(i.live||null!=s&&s.live){const o="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){An(s,i,this);const e=i.playlistParsingError;if(e){this.warn(e);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void s.trigger($s.ERROR,{type:Fs.NETWORK_ERROR,details:Ns.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=i.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=In(i,1e3*(i.edge-d));if(i.requestScheduled+c<n?i.requestScheduled=n:i.requestScheduled+=c,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let u,f,g;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,r=i.lastPartSn,a=i.endSN,l=i.lastPartIndex,h=r===a;-1!==l?h?(f=a+1,g=e?0:l):(f=r,g=e?l+1:i.maxPartIndex):f=a+1;const d=i.age,c=d+i.ageHeader;let p=Math.min(c-i.partTarget,1.5*i.targetduration);if(p>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${p} with playlist age: ${i.age}`),p=0;else{const e=Math.floor(p/i.targetduration);if(f+=e,void 0!==g){g+=Math.round(p%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${p} skip sn ${e} to part ${g}`)}i.tuneInGoal=p}if(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g),e||!h)return i.requestScheduled=n,void this.loadingPlaylist(o,u)}else(i.canBlockReload||i.canSkipUntil)&&(u=this.getDeliveryDirectives(i,t.deliveryDirectives,f,g));u&&void 0!==f&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(e,t)),a)}getDeliveryDirectives(e,t,s,i){let r=mr(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=fr),new vr(s,i,r)}checkRetry(e){const t=e.details,s=Ir(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Ur||!i.resolved&&r===$r);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Mr(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,i.resolved=!0}return o}}var Nn="NOT_LOADED",$n="APPENDING",Bn="PARTIAL",Un="OK";class Gn{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.BUFFER_APPENDED,this.onBufferAppended,this),e.on($s.FRAG_BUFFERED,this.onFragBuffered,this),e.on($s.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.BUFFER_APPENDED,this.onBufferAppended,this),e.off($s.FRAG_BUFFERED,this.onFragBuffered,this),e.off($s.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let t=s.length;t--;){const i=s[t];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some((e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(a.body),s})):this.removeFragment(a.body))}))}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const s=e.frag,i=Vn(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach((i=>{const a=s.elementaryStreams[i];if(!a)return;const o=t[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,e.part,l,o)})),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),Hn(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0;(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Wn(s,(t=>t.fragment.sn>=e)))}fragBuffered(e,t){const s=Vn(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<i.length;e++){const t=i.start(e)-this.bufferPadding,s=i.end(e)+this.bufferPadding;if(l>=t&&o<=s){r.time.push({startPTS:Math.max(n,i.start(e)),endPTS:Math.min(a,i.end(e))});break}if(n<s&&a>t){const t=Math.max(n,i.start(e)),s=Math.min(a,i.end(e));s>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:s}))}else if(a<=t)break}return r}getPartialFragment(e){let t,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&Hn(h)&&(s=h.body.start-a,i=h.body.end+a,e>=s&&e<=i&&(t=Math.min(e-s,i-e),n<=t&&(r=h.body,n=t)))})),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Hn(t))}getState(e){const t=Vn(e),s=this.fragments[t];return s?s.buffered?Hn(s)?Bn:Un:$n:Nn}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=Vn(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if("initSegment"===s.sn)return;const a=s.type;if(i){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Vn(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(e){const t=Vn(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=Wn(s,(e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((e=>e.clearElementaryStreamInfo()))}}function Hn(e){var t,s,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(s=e.range.audio)&&s.partial||null!=(i=e.range.audiovideo)&&i.partial)}function Vn(e){return`${e.type}_${e.level}_${e.sn}`}function Wn(e,t){return e.filter((e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s}))}class qn{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case en:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case tn:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class jn{constructor(){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.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let e=0;e<4;e++)s[e]=t.getUint32(4*e);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)u[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],p=u[o],m=u[p];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[m^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],p=u[2],m=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r==0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r==4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^p[d[y>>>8&255]]^m[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],p=c[3];const m=new Int32Array(e),v=new Int32Array(m.length);let y,E,S,T,_,L,b,R,A,P,w,I,D,C;const k=this.networkToHostOrderSwap;for(;t<m.length;){for(A=k(m[t]),P=k(m[t+1]),w=k(m[t+2]),I=k(m[t+3]),_=A^r[0],L=I^r[1],b=w^r[2],R=P^r[3],D=4,C=1;C<i;C++)y=o[_>>>24]^l[L>>16&255]^h[b>>8&255]^d[255&R]^r[D],E=o[L>>>24]^l[b>>16&255]^h[R>>8&255]^d[255&_]^r[D+1],S=o[b>>>24]^l[R>>16&255]^h[_>>8&255]^d[255&L]^r[D+2],T=o[R>>>24]^l[_>>16&255]^h[L>>8&255]^d[255&b]^r[D+3],_=y,L=E,b=S,R=T,D+=4;y=n[_>>>24]<<24^n[L>>16&255]<<16^n[b>>8&255]<<8^n[255&R]^r[D],E=n[L>>>24]<<24^n[b>>16&255]<<16^n[R>>8&255]<<8^n[255&_]^r[D+1],S=n[b>>>24]<<24^n[R>>16&255]<<16^n[_>>8&255]<<8^n[255&L]^r[D+2],T=n[R>>>24]<<24^n[_>>16&255]<<16^n[L>>8&255]<<8^n[255&b]^r[D+3],v[t]=k(y^u),v[t+1]=k(T^f),v[t+2]=k(S^g),v[t+3]=k(E^p),u=A,f=P,g=w,p=I,t+=4}return v.buffer}}class Kn{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=function(e){switch(e){case en:return"AES-CBC";case tn:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class zn{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise(((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==en||16!==t.byteLength)return ri.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Vi(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new jn),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Kn(this.subtle,t,i)}return this.fastAesKey.expandKey().then((t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new qn(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,t)})).catch((r=>(ri.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i))))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ri.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Yn=Math.pow(2,17);class Xn{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Zn({type:Fs.NETWORK_ERROR,details:Ns.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(Jn(e));e.gap=!1}const l=this.loader=r?new r(i):new n(i),h=Qn(e);e.loader=l;const d=xr(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Yn};e.stats=l.stats;const u={onSuccess:(t,s,i,r)=>{this.resetLoader(e,l);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,i,r,n)=>{this.resetLoader(e,l),o(new Zn({type:Fs.NETWORK_ERROR,details:Ns.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Qs({url:s,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,s,i)=>{this.resetLoader(e,l),o(new Zn({type:Fs.NETWORK_ERROR,details:Ns.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,s,i)=>{this.resetLoader(e,l),o(new Zn({type:Fs.NETWORK_ERROR,details:Ns.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:t}))}};t&&(u.onProgress=(s,i,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(h,c,u)}))}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Jn(e,t));const l=this.loader=r?new r(i):new n(i),h=Qn(e,t);e.loader=l;const d=xr(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Yn};t.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(e,l),o(new Zn({type:Fs.NETWORK_ERROR,details:Ns.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Qs({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Zn({type:Fs.NETWORK_ERROR,details:Ns.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(e,l),o(new Zn({type:Fs.NETWORK_ERROR,details:Ns.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})}))}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Qn(e,t=null){const s=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(Ms(r)&&Ms(n)){var a;let t=r,s=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(s=n+(16-e%16)),0!==r&&(i.resetIV=!0,t=r-16)}i.rangeStart=t,i.rangeEnd=s}var o;return i}function Jn(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:Fs.MEDIA_ERROR,details:Ns.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Zn(i)}class Zn extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class ea extends Js{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ta{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}const sa={length:0,start:()=>0,end:()=>0};class ia{static isBuffered(e,t){if(e){const s=ia.getBuffered(e);for(let e=s.length;e--;)if(t>=s.start(e)&&t<=s.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=ia.getBuffered(e);return ia.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=ia.bufferedRanges(e);if(i.length)return ia.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort(((e,t)=>e.start-t.start||t.end-e.end));let i=-1,r=[];if(s)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(i=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<s?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const h=r[e].start,d=r[e].end;if(-1===i&&t>=h&&t<=d&&(i=e),t+s>=h&&t<d)o=h,l=d,a=l-t;else if(t+s<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||sa}catch(e){return ri.log("failed to get media.buffered",e),sa}}}function ra(e,t){for(let i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function na(e,t){const s=e.start+t;e.startPTS=s,e.setStart(s),e.endPTS=s+e.duration}function aa(e,t){const s=t.fragments;for(let t=0,i=s.length;t<i;t++)na(s[t],e);t.fragmentHint&&na(t.fragmentHint,e),t.alignedSliding=!0}function oa(e,t){e&&(!function(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const s=Math.min(t.endCC,e.endCC),i=ra(t.fragments,s),r=ra(e.fragments,s);if(!i||!r)return;ri.log(`Aligning playlist at start of dicontinuity sequence ${s}`);aa(i.start-r.start,e)}(t,e),t.alignedSliding||function(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const s=e.fragments,i=t.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=ra(i,a),n=ra(s,a));r&&n||(r=i[Math.floor(i.length/2)],n=ra(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;aa((l-o)/1e3-(n.start-r.start),e)}(t,e),t.alignedSliding||t.skippedSegments||wn(e,t,!1))}function la(e,t,s){ha(e,t,s),e.addEventListener(t,s)}function ha(e,t,s){e.removeEventListener(t,s)}const da=function(e){let t="";const s=e.length;for(let i=0;i<s;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t},ca={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"};class ua extends ea{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ca.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=ia.bufferInfo(i||s,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${Ms(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===ca.ENDED)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,i=t.start-s,r=t.start+t.duration+s;if(o||r<a.start||i>a.end){const e=n>r;(n<i||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===ca.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Xn(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new zn(e.config)}registerListeners(){const{hls:e}=this;e.on($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($s.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($s.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===ca.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ca.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=ia.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return ia.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;la(s,"seeking",this.onMediaSeeking),la(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===ca.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ha(i,"seeking",this.onMediaSeeking),ha(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ca.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,(e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===ca.FRAG_LOADING||!this.fragCurrent&&t===ca.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=ca.IDLE):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger($s.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((t=>{this.state!==ca.STOPPED&&this.state!==ca.ERROR&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===$n){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Bn&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger($s.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:t}=this,{frag:s,payload:i}=e,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&sn(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,rn(r.method)).catch((e=>{throw t.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),e})).then((i=>{const r=self.performance.now();return t.trigger($s.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((t=>{this.state!==ca.STOPPED&&this.state!==ca.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==ca.STOPPED&&(this.state=ca.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,s=new Error("EME not supported (light build)");return this.warn(s.message),!e||e.mediaKeys?!1:(this.hls.trigger($s.ERROR,{type:Fs.KEY_SYSTEM_ERROR,details:Ns.KEY_SYSTEM_NO_KEYS,fatal:!0,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?da(ia.getBuffered(s)):"(detached)"})`),_i(e)){var i;if(e.type!==qs){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=ca.IDLE)}const t=null==(i=this.levels)?void 0:i[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=ca.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||0===r.length||r.some((e=>!e)),a=new ta(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=ca.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger($s.KEY_LOADED,e),this.state===ca.KEY_LOADING&&(this.state=ca.IDLE),e})),this.hls.trigger($s.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(_i(e)&&(!o||e.sn!==o.sn)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts&&_i(e)){const r=n.partList;if(r&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,s);if(o>-1){const l=r[o];let h;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=ca.FRAG_LOADING,h=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(e,l,t,i))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,i).catch((e=>this.handleFragLoadError(e))),this.hls.trigger($s.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}var l;if(_i(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter((e=>e.loaded)).map((e=>`[${e.start}-${e.end}]`))}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),Ms(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=ca.FRAG_LOADING;const h=this.config.progressive&&e.type!==qs;let d;return d=h&&a?a.then((t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,i))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,h?i:void 0),a]).then((([e])=>(!h&&i&&i(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger($s.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,s,i){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,i).then((i=>{o[t.index]=i;const n=i.part;this.hls.trigger($s.FRAG_LOADED,i);const a=Cn(s.details,e.sn,t.index+1)||kn(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===Ns.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Fs.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger($s.ERROR,t)}else this.hls.trigger($s.ERROR,{type:Fs.OTHER_ERROR,details:Ns.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==ca.PARSING)return void(this.fragCurrent||this.state===ca.STOPPED||this.state===ca.ERROR||(this.state=ca.IDLE));const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===qs)return!1;if(t>=r.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Cn(o,r,n):null,h=l?l.fragment:Dn(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==ca.PARSING)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=Vi(n,a)),!o.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:o};if(this.hls.trigger($s.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ia.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,i=ia.bufferInfo(t,s,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!Ms(i))return null;const r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,r)}getFwdBufferInfoAtPos(e,t,s,i){const r=ia.bufferInfo(e,t,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-t,i);return ia.bufferInfo(e,t,s)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-3*t,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=Vs){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const s=this.hls.startPosition,i=this.hls.liveSyncPosition,r=o?(-1!==s&&s>=n?s:i)||o.start:e;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}let h=this.filterReplacedPrimary(o,t);if(!h&&o){const e=o.sn-t.startSN;h=this.filterReplacedPrimary(s[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Un||s===Bn&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==e&&s.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){return this.config,!1}filterReplacedPrimary(e,t){return e?(this.config,e):e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${o.start}`),i=a),r=l}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!Ms(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const r=e[i];if(wr(t,s,r))return r}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:r}=e;let n;return r&&(i=i.concat(r)),Rr(i,(e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=s?1:e.start>s?-1:0))),n||null}return null}(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=Ar(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===Un||t===Bn&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn||!s.live)){if(c.level===r.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Un?t:null}}}return c}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&Ms(r);if(n||!a&&!r){oa(s,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&Ms(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&_i(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===ca.FRAG_LOADING_WAITING_RETRY)||(this.state=ca.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=t.details===Ns.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction;if(!a)return void(this.state=ca.ERROR);const{action:o,flags:l,retryCount:h=0,retryConfig:d}=a,c=!!d,u=c&&o===Ur,f=c&&!a.resolved&&l===Hr,g=null==(s=this.hls.latestLevelDetails)?void 0:s.live;if(!u&&f&&_i(i)&&!i.endList&&g&&!Cr(t))this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((u||f)&&h<d.maxNumRetry){var p;const s=Fr(null==(p=t.response)?void 0:p.code),r=Mr(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=ca.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${r}ms`)}else if(d){if(this.resetFragmentErrors(e),!(h<d.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${h})`);n||o===Br||(a.resolved=!0)}else this.state=o===$r?ca.WAITING_LEVEL:ca.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Fr(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ca.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===ca.PARSING||this.state===ca.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Ws&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ca.STOPPED&&(this.state=ca.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=ia.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===ca.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ca.STOPPED&&(this.state=ca.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce(((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=i?0:Rn(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger($s.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)){var n;const t=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===s.fragmentError||t&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),t){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=ca.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger($s.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Vs?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(null!=(i=t&&!s?e.startPTS:(s||e).start)?i:NaN).toFixed(3)}-${(null!=(r=t&&!s?e.endPTS:(s||e).end)?r:NaN).toFixed(3)}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class fa{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];i.push(e),1!==i.length||s||this.executeNext(t)}appendBlocker(e){return new Promise((t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)}))}prependBlocker(e){return new Promise((t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(e[0].execute(),e.splice(0,1))}))}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(t){var s;if(i.onError(t),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[e])?void 0:s.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map((e=>e.label)).join(", "))||""}}const ga=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,pa="HlsJsTrackRemovedError";class ma extends Error{constructor(e){super(e),this.name=pa}}function va(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function ya(e){return"audio"===e?1:0}class Ea{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on($s.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on($s.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($s.MANIFEST_PARSED,this.onManifestParsed,this),e.on($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($s.BUFFER_CODECS,this.onBufferCodecs,this),e.on($s.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off($s.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off($s.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($s.MANIFEST_PARSED,this.onManifestParsed,this),e.off($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($s.BUFFER_CODECS,this.onBufferCodecs,this),e.off($s.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Ms(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter(((t,s)=>this.isLevelAllowed(t)&&s<=e));return this.clientRect=null,Ea.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;let i=e.length-1;const r=Math.max(t,s);for(let t=0;t<e.length;t+=1){const s=e[t];if((s.width>=r||s.height>=r)&&(n=s,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){i=t;break}}var n,a;return i}}function Sa(e,t,s,i){e&&Object.keys(t).forEach((r=>{const n=e.filter((e=>e.groupId===r)).map((e=>{const n=Ys({},e);return n.details=void 0,n.attrs=new zr(n.attrs),n.url=n.attrs.URI=Ta(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=i,n}));e.push(...n)}))}function Ta(e,t,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}var _a,La={exports:{}};var ba=(_a||(_a=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function i(){}function r(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||e,a),l=s?s+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 a(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=s?s+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,r,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){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,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,n),!0;case 6:return d.fn.call(d.context,t,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),c){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,i);break;case 4:d[h].fn.call(d[h].context,t,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,i,r){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==t||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(La)),La.exports),Ra=ni(ba);class Aa{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:function(e,t){const s=new Uint8Array(t);let i=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Pa(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}function wa(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}function Ia(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function Da(e,t){const s=t;let i=0;for(;wa(e,t);){i+=10;i+=Ia(e,t+6),Pa(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(s,s+i)}function Ca(e,t){return 255===e[t]&&240==(246&e[t+1])}function ka(e,t){return 1&e[t+1]?7:9}function Ma(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function xa(e,t){return t+1<e.length&&Ca(e,t)}function Oa(e,t){if(xa(e,t)){const s=ka(e,t);if(t+s>=e.length)return!1;const i=Ma(e,t);if(i<=s)return!1;const r=t+i;return r===e.length||xa(e,r)}return!1}function Fa(e,t,s,i,r){if(!e.samplerate){const n=function(e,t,s,i){const r=t[s+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit($s.ERROR,$s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[s+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d=n;5!==a&&29!==a||(d-=3);const c=[a<<3|(14&d)>>1,(1&d)<<7|o<<3];return ri.log(`manifest codec:${i}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}(t,s,i,r);if(!n)return;Ys(e,n)}}function Na(e){return 9216e4/e}function $a(e,t,s,i,r){const n=i+r*Na(e.samplerate),a=function(e,t){const s=ka(e,t);if(t+s<=e.length){const i=Ma(e,t)-s;if(i>0)return{headerLength:s,frameLength:i}}}(t,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-t.length);h?(o=new Uint8Array(l-r),o.set(t.subarray(s+r,t.length),0)):o=t.subarray(s+r,s+l);const d={unit:o,pts:n};return h||e.samples.push(d),{sample:d,length:l,missing:h}}const l=t.length-s;o=new Uint8Array(l),o.set(t.subarray(s,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Ba(e,t){return wa(e,t)&&Ia(e,t+6)+10<=e.length-t}function Ua(e,t=0,s=1/0){return function(e,t,s,i){const r=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=(c=e,c&&c.buffer instanceof ArrayBuffer&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/n,l=(a+t)/n,h=Math.floor(Math.max(0,Math.min(l,o))),d=Math.floor(Math.min(h+Math.max(s,0),o));var c;return new i(r,h,d-h)}(e,t,s,Uint8Array)}function Ga(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const i=ci(Ua(e.data,1,s)),r=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=ci(Ua(e.data,3+s,n));let o;return o="--\x3e"===i?ci(Ua(e.data,4+s+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+s+n)),t.mimeType=i,t.pictureType=r,t.description=a,t.data=o,t}function Ha(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=ci(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=ci(e.data.subarray(t),!0);t+=s.length+1;const i=ci(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=ci(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Ga(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const s=ci(e.data.subarray(t),!0);t+=s.length+1;const i=ci(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=ci(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function Va(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=Ia(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}const Wa=10,qa=10;function ja(e){let t=0;const s=[];for(;wa(e,t);){const i=Ia(e,t+6);e[t+5]>>6&1&&(t+=Wa),t+=Wa;const r=t+i;for(;t+qa<r;){const i=Va(e.subarray(t)),r=Ha(i);r&&s.push(r),t+=i.size+Wa}Pa(e,t)&&(t+=Wa)}return s}function Ka(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function za(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function Ya(e){const t=ja(e);for(let e=0;e<t.length;e++){const s=t[e];if(Ka(s))return za(s)}}let Xa=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Qa(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Ja{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Vi(this.cachedData,e),this.cachedData=null);let s,i=Da(e,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?Ya(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Ms(o))&&(this.basePTS=Za(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Xa.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,s=r):r=l}else Ba(e,r)?(i=Da(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Xa.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const t=e.slice(s);this.cachedData?this.cachedData=Vi(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:Qa(),id3Track:a,textTrack:Qa()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Qa(),id3Track:this._id3Track,textTrack:Qa()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Za=(e,t,s)=>{if(Ms(e))return 90*e;return 9e4*t+(s?9e4*s.baseTime/s.timescale:0)};let eo=null;const to=[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],so=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],io=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ro=[0,1,1,4];function no(e,t,s,i,r){if(s+24>t.length)return;const n=ao(t,s);if(n&&s+n.frameLength<=t.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function ao(e,t){const s=e[t+1]>>3&3,i=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*to[14*(3===s?3-i:3===i?3:4)+r-1],h=so[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=io[s][i],u=ro[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===eo){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);eo=e?parseInt(e[1]):0}return!!eo&&eo<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function oo(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function lo(e,t){return t+1<e.length&&oo(e,t)}function ho(e,t){if(t+1<e.length&&oo(e,t)){const s=4,i=ao(e,t);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=t+r;return n===e.length||lo(e,n)}return!1}const co=/\/emsg[-/]ID3/i;function uo(e,t){return Ms(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class fo{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new zn(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,en)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)s.set(e.subarray(t,t+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)e.set(s.subarray(i,i+16),t);return e}decryptAvcSample(e,t,s,i,r){const n=zi(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)})).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void i();const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,i,n),this.decrypter.isSync())))return}}}}class go{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,i=s.length;if(!i)return void t.dropped++;{const t=s[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,h,d=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(t,0),r=0,d=1);d<i;)if(o=t[d++],r)if(1!==r)if(o)if(1===o){if(l=d-r-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const s=this.getLastNalUnit(e.samples);s&&(n&&d<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=Vi(s.data,t.subarray(0,l)),s.state=0))}d<i?(h=this.getNALuType(t,d),c=d,u=h,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(c>=0&&r>=0){const e={data:t.subarray(c,i),type:u,state:r};a.push(e)}if(0===a.length){const s=this.getLastNalUnit(e.samples);s&&(s.data=Vi(s.data,t))}return e.naluState=r,a}}class po{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&ri.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class mo extends go{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach((i=>{var r,l;switch(i.type){case 1:{let t=!1;n=!0;const r=i.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Ki(i.data,1,s.pts,t.samples);break;case 7:{var d,c;n=!0,o=!0;const t=i.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(d=e.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const i=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}})),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new po(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,i=8,r=8;for(let n=0;n<e;n++)0!==r&&(s=t.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(e){const t=new po(e);let s,i,r,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),d=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),m=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=c();if(3===e&&f(1),p(),p(),f(1),u())for(i=3!==e?8:12,r=0;r<i;r++)u()&&m(r<6?16:64,t)}p();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();p(),f(1);const E=c(),S=c(),T=d(1);0===T&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let _=[1,1];if(u()&&u()){switch(h()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-T)*(S+1)*16-(T?2:4)*(o+l),pixelRatio:_}}}const vo=188;class yo{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=yo.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(e){const t=e.length;let s=Math.min(940,t-vo)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<t;o+=vo){if(71!==e[o]||t-o!==vo&&71!==e[o+vo]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-vo)+1)),r||(r=0===Eo(e,o)),r&&a>1&&(0===n&&a>2||o+vo>s))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:wi[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=yo.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=yo.createTrack("audio",i),this._id3Track=yo.createTrack("id3"),this._txtTrack=yo.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Vi(this.remainderData,e)).length,this.remainderData=null),y<vo&&!i)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,yo.syncOffset(e));y-=(y-E)%vo,y<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let S=0;for(let t=E;t<y;t+=vo)if(71===e[t]){const i=!!(64&e[t+1]),y=Eo(e,t);let S;if((48&e[t+3])>>4>1){if(S=t+5+e[t+4],S===t+vo)continue}else S=t+4;switch(y){case h:i&&(d&&(r=bo(d,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(S,t+vo)),d.size+=t+vo-S);break;case c:if(i){if(f&&(r=bo(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(S,t+vo)),f.size+=t+vo-S);break;case u:i&&(g&&(r=bo(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(S,t+vo)),g.size+=t+vo-S);break;case 0:i&&(S+=e[S]+1),v=this._pmtId=So(e,S);break;case v:{i&&(S+=e[S]+1);const r=To(e,S,this.typeSupported,s,this.observer,this.logger);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===p||m||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${p}'. Backtracking to sync byte @${E} to parse all TS packets.`),p=null,t=E-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=y}}else S++;S>0&&_o(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const T={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(T),T}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,a=t.pesData,o=i.pesData;let l;if(n&&(l=bo(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,a&&(l=bo(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=bo(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new fo(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){null===this.videoParser&&"avc"===e&&(this.videoParser=new mo)}decrypt(e,t){return new Promise((s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,(()=>{s(e)})):s(e)})):r.samples&&t.decryptAvcSamples(r.samples,0,0,(()=>{s(e)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r,n,a,o=t.data;if(i){this.aacOverFlow=null;const t=i.missing,r=i.sample.unit.byteLength;if(-1===t)o=Vi(i.sample.unit,o);else{const n=r-t;i.sample.unit.set(o.subarray(0,t),n),e.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!xa(o,r);r++);if(r!==s){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",_o(this.observer,new Error(e),t,this.logger),!t)return}if(Fa(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Na(e.samplerate);a=i.sample.pts+t}}let l,h=0;for(;r<n;){if(l=$a(e,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<n-1&&!xa(o,r);r++);}}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(lo(s,n)){const t=no(e,s,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=Ys({},t,{type:this._videoTrack?Xa.emsg:Xa.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Eo(e,t){return((31&e[t+1])<<8)+e[t+2]}function So(e,t){return(31&e[t+10])<<8|e[t+11]}function To(e,t,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Eo(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Lo("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!i){Lo("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Lo("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(-1===a.audioPid&&l>0){let s=t+5,i=l;for(;i>2;){if(106===e[s])n.warn("AC-3 in M2TS support not included in build");const t=e[s+1]+2;s+=t,i-=t}}break;case 194:case 135:return _o(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:return _o(r,new Error("Unsupported HEVC in M2TS found"),void 0,n),a}t+=l+5}return a}function _o(e,t,s,i){i.warn(`parsing error: ${t.message}`),e.emit($s.ERROR,$s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:t,reason:t.message})}function Lo(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function bo(e,t){let s,i,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Vi(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>e.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let d=r+9;if(e.size<=d)return null;e.size-=d;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(d){if(d>t){d-=t;continue}s=s.subarray(d),t-=d,d=0}c.set(s,o),o+=t}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}class Ro{static getSilentFrame(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])}}}const Ao=Math.pow(2,32)-1;class Po{static init(){let e;for(e in Po.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Po.types)Po.types.hasOwnProperty(e)&&(Po.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=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]),s=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]);Po.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Po.STTS=Po.STSC=Po.STCO=r,Po.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Po.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Po.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Po.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Po.FTYP=Po.box(Po.types.ftyp,n,o,n,a),Po.DINF=Po.box(Po.types.dinf,Po.box(Po.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return Po.box(Po.types.hdlr,Po.HDLR_TYPES[e])}static mdat(e){return Po.box(Po.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Ao+1)),i=Math.floor(t%(Ao+1));return Po.box(Po.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(e){return Po.box(Po.types.mdia,Po.mdhd(e.timescale||0,e.duration||0),Po.hdlr(e.type),Po.minf(e))}static mfhd(e){return Po.box(Po.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Po.box(Po.types.minf,Po.box(Po.types.smhd,Po.SMHD),Po.DINF,Po.stbl(e)):Po.box(Po.types.minf,Po.box(Po.types.vmhd,Po.VMHD),Po.DINF,Po.stbl(e))}static moof(e,t,s){return Po.box(Po.types.moof,Po.mfhd(e),Po.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=Po.trak(e[t]);return Po.box.apply(null,[Po.types.moov,Po.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(Po.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=Po.trex(e[t]);return Po.box.apply(null,[Po.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Ao+1)),i=Math.floor(t%(Ao+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Po.box(Po.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Po.box(Po.types.sdtp,s)}static stbl(e){return Po.box(Po.types.stbl,Po.stsd(e),Po.box(Po.types.stts,Po.STTS),Po.box(Po.types.stsc,Po.STSC),Po.box(Po.types.stsz,Po.STSZ),Po.box(Po.types.stco,Po.STCO))}static avc1(e){let t,s,i,r=[],n=[];for(t=0;t<e.sps.length;t++)s=e.sps[t],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(t=0;t<e.pps.length;t++)s=e.pps[t],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=Po.box(Po.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return Po.box(Po.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,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Po.box(Po.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Po.box(Po.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return Po.box(Po.types.mp4a,Po.audioStsd(e),Po.box(Po.types.esds,Po.esds(e)))}static mp3(e){return Po.box(Po.types[".mp3"],Po.audioStsd(e))}static ac3(e){return Po.box(Po.types["ac-3"],Po.audioStsd(e),Po.box(Po.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return Po.box(Po.types.stsd,Po.STSD,Po.mp4a(e));if("mp3"===t&&"mp3"===e.codec)return Po.box(Po.types.stsd,Po.STSD,Po.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return Po.box(Po.types.stsd,Po.STSD,Po.avc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(Ao+1)),a=Math.floor(s%(Ao+1));return Po.box(Po.types.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const s=Po.sdtp(e),i=e.id,r=Math.floor(t/(Ao+1)),n=Math.floor(t%(Ao+1));return Po.box(Po.types.traf,Po.box(Po.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),Po.box(Po.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Po.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,Po.box(Po.types.trak,Po.tkhd(e),Po.mdia(e))}static trex(e){const t=e.id;return Po.box(Po.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<i;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Po.box(Po.types.trun,n)}static initSegment(e){Po.types||Po.init();const t=Po.moov(e);return Vi(Po.FTYP,t)}static hvc1(e){return new Uint8Array}}Po.types=void 0,Po.HDLR_TYPES=void 0,Po.STTS=void 0,Po.STSC=void 0,Po.STCO=void 0,Po.STSZ=void 0,Po.VMHD=void 0,Po.SMHD=void 0,Po.STSD=void 0,Po.FTYP=void 0,Po.DINF=void 0;function wo(e,t=!1){return function(e,t,s=1,i=!1){const r=e*t*s;return i?Math.round(r):r}(e,1e3,1/9e4,t)}function Io(e){const{baseTime:t,timescale:s,trackId:i}=e;return`${t/s} (${t}/${s}) trackId: ${i}`}let Do,Co=null,ko=null;function Mo(e,t,s,i){return{duration:t,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class xo extends Js{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,null===Co){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Co=e?parseInt(e[1]):0}if(null===ko){const e=navigator.userAgent.match(/Safari\/(\d+)/i);ko=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?Io(t):t} > ${e?Io(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce(((e,i)=>{let r=i.pts,n=r-e;return n<-4294967296&&(t=!0,r=Oo(r,s),n=r-e),n>0?e:r}),s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,p=r;const m=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!m||E)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var T,_,L,b;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(_=e.pixelRatio)?void 0:_[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(b=e.pixelRatio)?void 0:b[1]))||!e&&S||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,n));const s=this.isVideoContiguous;let i,a=-1;if(S&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,p+=(t.samples[0].pts-e)/t.inputTimeScale,i=p}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&S){const s=this.getVideoStartPts(t.samples),i=(Oo(e.samples[0].pts,s)-s)/t.inputTimeScale;g+=Math.max(0,i),p+=Math.max(0,-i)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||S||o===Ws?p:void 0),S){const i=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,s,i)}}else S&&(l=this.remuxVideo(t,p,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Fo(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=No(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Oo(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4",g=-1;if(u&&(h=d=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Po.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,c=e.inputTimeScale,l&&c===l.timescale?u=!1:h=d=this.computeInitPts(r[0].pts,c,s,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Po.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Oo(n[0].dts,e),i=this.computeInitPts(t,c,s,"video"),r=this.computeInitPts(e,c,s,"video");d=Math.min(d,i),h=Math.min(h,r)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${h/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/c} (${h}/${c}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:c,trackId:g},this._initDTS={baseTime:d,timescale:c,trackId:g}):h=c=void 0,{tracks:o,initPTS:h,timescale:c,trackId:g}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let d,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!s||null===u){const e=h+t*r,i=n[0].pts-Oo(n[0].dts,n[0].pts);Co&&null!==u&&Math.abs(e-i-(u+h))<15e3?s=!0:u=e-i-h}const y=u+h;for(let e=0;e<o;e++){const t=n[e];t.pts=Oo(t.pts,y),t.dts=Oo(t.dts,y),t.dts<n[e>0?e-1:e].dts&&(v=!0)}v&&n.sort((function(e,t){const s=e.dts-t.dts,i=e.pts-t.pts;return s||i})),d=n[0].dts,c=n[n.length-1].dts;const E=c-d,S=E?Math.round(E/(o-1)):g||e.inputTimeScale/30;if(s){const s=d-y,i=s>S,r=s<-1;if((i||r)&&(i?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wo(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wo(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||y>=n[0].pts||Co)){d=y;const e=n[0].pts-s;if(i)n[0].dts=d,n[0].pts=e;else{let t=!0;for(let i=0;i<n.length&&!(n[i].dts>e&&t);i++){const e=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i<n.length-1){const s=n[i+1].pts;t=s<=n[i].pts==s<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${wo(e,!0)}/${wo(d,!0)}, delta: ${wo(s,!0)} ms`)}}d=Math.max(0,d);let T=0,_=0,L=d;for(let e=0;e<o;e++){const t=n[e],s=t.units,i=s.length;let r=0;for(let e=0;e<i;e++)r+=s[e].data.length;_+=r,T+=i,t.length=r,t.dts<L?(t.dts=L,L+=S/4|0||1):L=t.dts,p=Math.min(t.pts,p),m=Math.max(t.pts,m)}c=n[o-1].dts;const b=_+4*T+8;let R;try{R=new Uint8Array(b)}catch(e){return void this.observer.emit($s.ERROR,$s.ERROR,{type:Fs.MUX_ERROR,details:Ns.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:b,reason:`fail allocating video mdat ${b}`})}const A=new DataView(R.buffer);A.setUint32(0,b),R.set(Po.types.mdat,4);let P=!1,w=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,D=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],s=t.units;let l,d=0;for(let e=0,t=s.length;e<t;e++){const t=s[e],i=t.data,r=t.data.byteLength;A.setUint32(f,r),f+=4,R.set(i,f),f+=r,d+=4+r}if(e<o-1)g=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const s=this.config,a=e>0?t.dts-n[e-1].dts:S;if(l=e>0?t.pts-n[e-1].pts:S,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(s.maxBufferHole*r),n=(i?p+i*r:this.nextAudioTs+h)-t.pts;n>e?(g=n-a,g<0?g=a:P=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const c=Math.round(t.pts-t.dts);w=Math.min(w,g),D=Math.max(D,g),I=Math.min(I,l),C=Math.max(C,l),a.push(Mo(t.key,g,d,c))}if(a.length)if(Co){if(Co<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(ko&&C-I<D-w&&S/D<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=d;for(let t=0,s=a.length;t<s;t++){const i=e+a[t].duration,r=e+a[t].cts;if(t<s-1){const e=i+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:S;a[t].cts=0,e=i}}g=P||!g?S:g;const k=c+g;this.nextVideoTs=u=k-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const M={data1:Po.moof(e.sequenceNumber++,d,Ys(e,{samples:a})),data2:R,startPTS:(p-h)/r,endPTS:(m+g-h)/r,startDTS:(d-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,M}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=e.samples,g=d?0:8,p=this.nextAudioTs||-1;const m=h.baseTime*n/h.timescale,v=m+t*n;if(this.isAudioContiguous=s=s||f.length&&p>0&&(i&&Math.abs(v-(p+m))<9e3||Math.abs(Oo(f[0].pts,v)-(p+m))<20*l),f.forEach((function(e){e.pts=Oo(e.pts,v)})),!s||p<0){const e=f.length;if(f=f.filter((e=>e.pts>=0)),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${m} / ${n})`),!f.length)return;p=0===r?0:i&&!u?Math.max(0,v-m):f[0].pts-m}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,i=p+m;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,h=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===s&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=p=a-m,i=a);else if(o>=t*l&&h<1e4&&u){let t=Math.round(o/l);for(i=a-t*l;i<0&&t&&l;)t--,i+=l;0===s&&(this.nextAudioTs=p=i-m),this.warn(`Injecting ${t} audio frames @ ${((i-m)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=Ro.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),f.splice(s,0,{unit:t,pts:i}),i+=l,s++}}r.pts=i,i+=l}}let y,E=null,S=null,T=0,_=f.length;for(;_--;)T+=f[_].unit.byteLength;for(let t=0,i=f.length;t<i;t++){const i=f[t],r=i.unit;let n=i.pts;if(null!==S){c[t-1].duration=Math.round((n-S)/a)}else{if(s&&"aac"===e.segmentCodec&&(n=p+m),E=n,!(T>0))return;T+=g;try{y=new Uint8Array(T)}catch(e){return void this.observer.emit($s.ERROR,$s.ERROR,{type:Fs.MUX_ERROR,details:Ns.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:T,reason:`fail allocating audio mdat ${T}`})}if(!d){new DataView(y.buffer).setUint32(0,T),y.set(Po.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,c.push(Mo(!0,o,l,0)),S=n}const L=c.length;if(!L)return;const b=c[c.length-1];p=S-m,this.nextAudioTs=p+a*b.duration;const R=d?new Uint8Array(0):Po.moof(e.sequenceNumber++,E/a,Ys({},e,{samples:c}));e.samples=[];const A=(E-m)/n,P=this.nextAudioTs/n,w={data1:R,data2:y,startPTS:A,endPTS:P,startDTS:A,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,w}}function Oo(e,t){let s;if(null===t)return e;for(s=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=s;return e}function Fo(e,t,s,i){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=Oo(r.pts-s.baseTime*n/s.timescale,t*n)/n,r.dts=Oo(r.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function No(e,t,s){const i=e.samples.length;if(!i)return;const r=e.inputTimeScale;for(let n=0;n<i;n++){const i=e.samples[n];i.pts=Oo(i.pts-s.baseTime*r/s.timescale,t*r)/r}e.samples.sort(((e,t)=>e.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}function $o(e,t,s=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(s?e.duration:0))/e.timescale:t}function Bo(e,t,s){const i=e.codec;if(i&&i.length>4)return i;if(t===yi){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return nr(i,!1)}return s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{Do=self.performance.now.bind(self.performance)}catch(e){Do=Date.now}const Uo=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Qa("video",1),n=this.audioTrack=Qa("audio",1),a=this.txtTrack=Qa("text",1);if(this.id3Track=Qa("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=Fi(e);if(o.video){const{id:e,timescale:t,codec:s,supplemental:i}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=s,r.supplemental=i}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=wi.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let s=0;s<t;){const i=Ci(e,s);if(i>8&&109===e[s+4]&&111===e[s+5]&&111===e[s+6]&&102===e[s+7])return!0;s=i>1?s+i:t}return!1}(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Vi(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},s=xi(e,["moof"]);if(s.length<2)return t.remainder=e,t;const i=s[s.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(s);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Wi(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Wi(e,t),{videoTrack:t,audioTrack:Qa(),id3Track:i,textTrack:Qa()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=xi(e.samples,["emsg"]);i&&i.forEach((e=>{const i=function(e){const t=e[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==Ii(e.subarray(h,h+1));)s+=Ii(e.subarray(h,h+1)),h+=1;for(s+=Ii(e.subarray(h,h+1)),h+=1;"\0"!==Ii(e.subarray(h,h+1));)i+=Ii(e.subarray(h,h+1)),h+=1;i+=Ii(e.subarray(h,h+1)),h+=1,r=Ci(e,12),n=Ci(e,16),o=Ci(e,20),l=Ci(e,24),h=28}else if(1===t){h+=4,r=Ci(e,h),h+=4;const t=Ci(e,h);h+=4;const n=Ci(e,h);for(h+=4,a=2**32*t+n,xs(a)||(a=Number.MAX_SAFE_INTEGER,ri.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ci(e,h),h+=4,l=Ci(e,h),h+=4;"\0"!==Ii(e.subarray(h,h+1));)s+=Ii(e.subarray(h,h+1)),h+=1;for(s+=Ii(e.subarray(h,h+1)),h+=1;"\0"!==Ii(e.subarray(h,h+1));)i+=Ii(e.subarray(h,h+1)),h+=1;i+=Ii(e.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(co.test(i.schemeIdUri)){const e=uo(i,t);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:Xa.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=uo(i,t);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:e,pts:e,type:Xa.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends Js{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=Fi(e);if(t)!function(e,t){if(!e||!t)return;const s=t.keyId;s&&t.isCommonEncryption&&Hi(e,((e,t)=>{const i=e.subarray(8,24);i.some((e=>0!==e))||(ri.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${ui(i)} -> ${ui(s)}`),e.set(s,8))}))}(e,t);else{const e=r||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(s=Bo(r,yi,this)),n&&(i=Bo(n,Ei,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};Ms(h)||(h=this.lastEndTime=r||0);const c=t.samples;if(!c.length)return d;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,s){const i={},r=xi(e,["moof","traf"]);for(let e=0;e<r.length;e++){const n=r[e],a=xi(n,["tfhd"])[0],o=Ci(a,4),l=t[o];if(!l)continue;i[o]||(i[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=i[o],d=xi(n,["tfdt"])[0];if(d){const e=d[0];let t=Ci(d,4);1===e&&(t===Ai?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=Ai+1,t+=Ci(d,8))),Ms(t)&&(!Ms(h.start)||t<h.start)&&(h.start=t)}const c=l.default,u=Ci(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=Ci(a,2&u?12:8));const g=xi(n,["trun"]);let p=h.start||0,m=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],s=Ci(t,4),i=h.sampleCount;h.sampleCount+=s;const r=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],d=8&t[2];let c=8,u=s;for(r&&(c+=4),n&&s&&(1&t[c+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=i),c+=4,a?(v=Ci(t,c),c+=4):v=f,o&&(c+=4),d&&(c+=4),p+=v,m+=v,u--);u--;)a?(v=Ci(t,c),c+=4):v=f,o&&(c+=4),l&&(1&t[c+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(u+1),h.keyFrameStart=p),c+=4),d&&(c+=4),p+=v,m+=v;!m&&f&&(m+=f*s)}h.duration+=m}if(!Object.keys(i).some((e=>i[e].duration))){let t=1/0,s=0;const r=xi(e,["sidx"]);for(let e=0;e<r.length;e++){const i=Oi(r[e]);if(null!=i&&i.references){t=Math.min(t,i.earliestPresentationTime/i.timescale);const e=i.references.reduce(((e,t)=>e+t.info.duration||0),0);s=Math.max(s,e+i.earliestPresentationTime/i.timescale)}}s&&Ms(s)&&Object.keys(i).forEach((e=>{i[e].duration||(i[e].duration=s*i[e].timescale-i[e].start)}))}return i}(c,f,this),p=f.audio?g[f.audio.id]:null,m=f.video?g[f.video.id]:null,v=$o(m,1/0),y=$o(p,1/0),E=$o(m,0,!0),S=$o(p,0,!0);let T=r,_=0;const L=p&&(!m||!l&&y<v||l&&l.trackId===f.audio.id),b=L?p:m;if(b){const e=b.timescale,t=b.start-r*e,s=L?f.audio.id:f.video.id;T=b.start/e,_=L?S-y:E-v,!n&&l||!function(e,t,s,i){if(null===e)return!0;const r=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>r}(l,T,r,_)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${T-r} (${t}/${e}) trackId: ${s}`),l=null,u.initPTS=t,u.timescale=e,u.trackId=s)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=T,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const R=T-l.baseTime/l.timescale,A=R+_;_>0?this.lastEndTime=A:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const P=!!f.audio,w=!!f.video;let I="";P&&(I+="audio"),w&&(I+="video");const D={data1:c,startPTS:R,startDTS:R,endPTS:A,endDTS:A,type:I,hasAudio:P,hasVideo:w,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};d.audio=P&&!w?D:void 0,d.video=w?D:void 0;const C=null==m?void 0:m.sampleCount;if(C){const e=m.keyFrameIndex,t=-1!==e;D.nb=C,D.dropped=0===e||this.isVideoContiguous?0:t?e:C,D.independent=t,D.firstKeyFrame=e,t&&m.keyFrameStart&&(D.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),D.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${C} dropped: ${D.dropped} start: ${D.firstKeyFramePTS||"NA"}`)}return d.initSegment=u,d.id3=Fo(s,r,l,l),i.samples.length&&(d.text=No(i,r,l)),d}}},{demux:yo,remux:xo},{demux:class extends Ja{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Da(e,0);let i=(null==s?void 0:s.length)||0;if(ho(e,i))return!1;for(let s=e.length;i<s;i++)if(Oa(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Ca(e,t)&&Ma(e,t)<=e.length-t}(e,t)}appendFrame(e,t,s){Fa(e,this.observer,t,s,e.manifestCodec);const i=$a(e,t,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:xo},{demux:class extends Ja{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Da(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==Ya(t)&&((e,t)=>{let s=0,i=5;t+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],t+=1,i-=o}return s})(e,s)<=16)return!1;for(let t=e.length;s<t;s++)if(ho(e,s))return ri.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return oo(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return no(e,t,s,this.basePTS,this.frameIndex)}},remux:xo}];class Go{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Do();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=o,E=function(e,t){let s=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t);return s}(n,t);if(E&&sn(E.method)){const e=this.getDecrypter(),t=rn(E.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer,t).then((e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t})),this.decryptionPromise;{let i=e.softwareDecrypt(n,E.key.buffer,E.iv.buffer,t);if(s.part>-1){const t=e.flush();i=t?t.buffer:t}if(!i)return r.executeEnd=Do(),Ho(s);n=new Uint8Array(i)}}const S=this.needsProbing(h,d);if(S){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit($s.ERROR,$s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=Do(),Ho(s)}(h||d||f||S)&&this.resetInitSegment(y,g,p,v,t),(h||f||S)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const T=this.transmux(n,E,u,c,s);this.asyncResult=Vo(T);const _=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,r.executeEnd=Do(),T}flush(e){const t=e.transmuxing;t.executeStart=Do();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then((()=>this.flush(e)));const n=[],{timeOffset:a}=i;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Do();const s=[Ho(e)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a);return Vo(h)?(this.asyncResult=!0,h.then((t=>(this.flushRemux(n,t,e),n)))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===Vs?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Do()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,s,i),a.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,s,i,r):this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,i,!1,this.id),chunkMeta:r})))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let t=0,s=Uo.length;t<s;t++){var n;if(null!=(n=Uo[t].demux)&&n.probe(e,this.logger)){r=Uo[t];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,h=r.demux;o&&o instanceof l||(this.remuxer=new l(s,t,i,this.logger)),a&&a instanceof h||(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new zn(this.config)),e}}const Ho=e=>({remuxResult:{},chunkMeta:e});function Vo(e){return"then"in e&&e.then instanceof Function}class Wo{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class qo{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}const jo=/(\d+)-(\d+)\/(\d+)/;class Ko{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||zo,this.controller=new self.AbortController,this.stats=new vi}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Ys({},e.headers))};e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return s}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&Ms(o)?o:l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))}),t.timeout);(Vo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var r;this.response=this.loader=s;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))}),l-(a-i.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new Yo(t||"fetch, bad network response",e,s)}i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=jo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Ms(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(s.headers)||i.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&Ms(t.highWaterMark)?this.loadProgressively(s,i,e,t.highWaterMark,o):n?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=s[a];l&&(i.loaded=i.total=l);const h={url:o.url,data:s,code:o.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!Ms(t.highWaterMark)&&d(i,e,s,o),null==(n=this.callbacks)||n.onSuccess(h,i,e,o)})).catch((t=>{var s;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(s=this.callbacks)||s.onError({code:r,text:n},e,t?t.details:null,i)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new Aa,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,l.buffer,e),o()})).catch((()=>Promise.reject()));return o()}}function zo(e,t){return new self.Request(e.url,t)}class Yo extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Xo=/^age:\s*[\d.]+\s*$/im;class Qo{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new vi,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,t.url)})).catch((e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r(s,t.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)})).catch((e=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:e.message},t,s,i)})):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[t]);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,self.clearTimeout(this.requestTimeout),s.timeout=r&&Ms(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,l="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=null!=l?l:t.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,e,r,t);const h={url:t.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(h,s,e,t))}}const h=r.loadPolicy.errorRetry;var o;if(Or(h,s.retry,!1,{url:e.url,data:void 0,code:i}))this.retry(h);else ri.error(`${i} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:i,text:t.statusText},e,t,s)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Or(e,this.stats.retry,!0))this.retry(e);else{var t;ri.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Mr(e,s.retry),s.retry++,ri.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Xo.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Jo={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Zo=Qs(Qs({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Qo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends Js{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,h=i?i.duration:s.duration,d=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,p=!!e||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(d<=Math.max(v,h/(2*y)*1e3))return;const E=m?m.len/y:0,S=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&S>-1,_=this.getBwEstimate(),L=r.levels,b=L[u],R=Math.max(l.loaded,Math.round(h*(s.bitrate||b.averageBitrate)/8));let A=T?d-S:d;A<1&&T&&(A=Math.min(d,8*l.loaded/_));const P=T?1e3*l.loaded/A:0,w=v/1e3,I=P?(R-l.loaded)/P:8*R/_+w;if(I<=E)return;const D=P?8*P:_,C=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),k=this.hls.config.abrBandWidthUpFactor;let M,x=Number.POSITIVE_INFINITY;for(M=u-1;M>c;M--){const e=L[M].maxBitrate,t=!L[M].details||C;if(x=this.getTimeToLoadFrag(w,D,h*e,t),x<Math.min(E,h+w))break}if(x>=I)return;if(x>10*h)return;T?this.bwEstimator.sample(d-Math.min(v,S),l.loaded):this.bwEstimator.sampleTTFB(d);const O=L[M].maxBitrate;this.getBwEstimate()*k>O&&this.resetEstimator(O);const F=this.findBestLevel(O,c,M,0,E,1,1);F>-1&&(M=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${E.toFixed(3)} s\n Estimated load time for current fragment: ${I.toFixed(3)} s\n Estimated load time for down switch fragment: ${x.toFixed(3)} s\n TTFB estimate: ${0|S} ms\n Current BW estimate: ${Ms(_)?0|_:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|O} bps`),r.nextLoadLevel=r.nextAutoLevel=M,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===M&&M>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,M>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,M,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||I>2*x?N():this.timer=self.setInterval(N,1e3*x),r.trigger($s.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Ks(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.FRAG_LOADING,this.onFragLoading,this),e.on($s.FRAG_LOADED,this.onFragLoaded,this),e.on($s.FRAG_BUFFERED,this.onFragBuffered,this),e.on($s.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($s.LEVEL_LOADED,this.onLevelLoaded,this),e.on($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($s.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on($s.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.FRAG_LOADING,this.onFragLoading,this),e.off($s.FRAG_LOADED,this.onFragLoaded,this),e.off($s.FRAG_BUFFERED,this.onFragBuffered,this),e.off($s.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($s.LEVEL_LOADED,this.onLevelLoaded,this),e.off($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($s.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off($s.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case Ns.BUFFER_ADD_CODEC_ERROR:case Ns.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Ns.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:i}=this;if(e&&s&&e.sn===s.sn&&e.level===s.level){const t=performance.now(),s=i?i.stats:e.stats,r=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;Ms(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===Vs&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=s?s.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered($s.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Vs||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===f.length)return 0;const v=f[d],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),E=-1===p||-1===h;let S,T="SDR",_=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:b}=m;this.audioTracksByGroup||(this.audioTracksByGroup=Lr(g));let R=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(e,t,s,i){return e.slice(s,i+1).reduce(((e,t,s)=>{if(!t.codecSet)return e;const i=t.audioGroups;let r=e[t.codecSet];r||(e[t.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,t.bitrate);const n=Math.min(t.height,t.width);return r.minHeight=Math.min(r.minHeight,n),r.minFramerate=Math.min(r.minFramerate,t.frameRate),r.minIndex=Math.min(r.minIndex,s),r.maxScore=Math.max(r.maxScore,t.score),r.fragmentError+=t.fragmentError,r.videoRanges[t.videoRange]=(r.videoRanges[t.videoRange]||0)+1,e}),{})}(f,0,t,s)),r=function(e,t,s,i,r){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let d=!1,c=!1,u=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:E}=Sr(t,r);for(let t=n.length;t--;){const s=e[n[t]];d||(d=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate),E.filter((e=>s.videoRanges[e]>0)).length>0&&(c=!0)}u=Ms(u)?u:0,f=Ms(f)?f:0;const S=Math.max(1080,u),T=Math.max(30,f);g=Ms(g)?g:s,s=Math.max(g,s),c||(t=void 0);const _=n.length>1;return{codecSet:n.reduce(((t,i)=>{const r=e[i];if(i===t)return t;if(v=c?E.filter((e=>r.videoRanges[e]>0)):[],_){if(r.minBitrate>s)return _r(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),t;if(!r.hasDefaultAudio)return _r(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return _r(i,`audio codec preference "${o}" not found`),t;if(a&&!h){if(!r.channels[a])return _r(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||h)&&d&&0===r.channels[2])return _r(i,"no renditions with stereo sound found"),t;if(r.minHeight>S)return _r(i,`min resolution of ${r.minHeight} > maximum of ${S}`),t;if(r.minFramerate>T)return _r(i,`min framerate of ${r.minFramerate} > maximum of ${T}`),t;if(!v.some((e=>r.videoRanges[e]>0)))return _r(i,`no variants with VIDEO-RANGE of ${Tr(v)} found`),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return _r(i,`video codec preference "${l}" not found`),t;if(r.maxScore<m)return _r(i,`max score of ${r.maxScore} < selected max of ${m}`),t}return t&&(sr(i)>=sr(t)||r.fragmentError>e[t].fragmentError)?t:(p=r.minIndex,m=r.maxScore,i)}),void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(i,T,e,L,b),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:d}=r;R=h,S=n,T=d?a[a.length-1]:a[0],_=o,e=Math.max(e,l),this.log(`picked start tier ${Tr(r)}`)}else S=null==v?void 0:v.codecSet,T=null==v?void 0:v.videoRange;const A=u?u.duration:c?c.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let o=s;o>=t;o--){var I;const t=f[o],c=o>d;if(!t)continue;if((S&&t.codecSet!==S||T&&t.videoRange!==T||c&&_>t.frameRate||!c&&_>0&&_<t.frameRate||null!=(I=t.supportedResult)&&null!=(I=I.decodingInfoResults)&&I.some((e=>!1===e.smooth)))&&(!E||o!==R)){w.push(o);continue}const g=t.details,m=(u?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||A;let v;v=c?a*e:n*e;const L=A&&i>=2*A&&0===r?t.averageBitrate:t.maxBitrate,b=this.getTimeToLoadFrag(P,v,L*m,void 0===g);if(v>=L&&(o===h||0===t.loadError&&0===t.fragmentError)&&(b<=P||!Ms(b)||y&&!this.bitrateTestDelay||b<l)){const e=this.forcedAutoLevel;return o===p||-1!==e&&e===p||(w.length&&this.trace(`Skipped level(s) ${w.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[w[0]].codecs}" ${f[w[0]].videoRange}; not compatible with "${S}" ${T}`),this.info(`switch candidate:${d}->${o} adjustedbw(${Math.round(v)})-bitrate=${Math.round(v-L)} ttfb:${P.toFixed(1)} avgDuration:${m.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${b.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},bufferController:class extends Js{constructor(e,t){var s;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger($s.MEDIA_ATTACHED,{media:t,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(s=di(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on($s.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.MANIFEST_PARSED,this.onManifestParsed,this),e.on($s.BUFFER_RESET,this.onBufferReset,this),e.on($s.BUFFER_APPENDING,this.onBufferAppending,this),e.on($s.BUFFER_CODECS,this.onBufferCodecs,this),e.on($s.BUFFER_EOS,this.onBufferEos,this),e.on($s.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($s.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($s.FRAG_PARSED,this.onFragParsed,this),e.on($s.FRAG_CHANGED,this.onFragChanged,this),e.on($s.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($s.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.MANIFEST_PARSED,this.onManifestParsed,this),e.off($s.BUFFER_RESET,this.onBufferReset,this),e.off($s.BUFFER_APPENDING,this.onBufferAppending,this),e.off($s.BUFFER_CODECS,this.onBufferCodecs,this),e.off($s.BUFFER_EOS,this.onBufferEos,this),e.off($s.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($s.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($s.FRAG_PARSED,this.onFragParsed,this),e.off($s.FRAG_CHANGED,this.onFragChanged,this),e.off($s.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?Ys(s,i.tracks):this.sourceBuffers.forEach((e=>{const[t]=e;t&&(s[t]=Ys({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null})),{media:e,mediaSource:t,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=di(this.appendSource);if(i){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(r),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&r instanceof t,va(s),function(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then((()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()}))};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Tr(s,((e,t)=>"initSegment"===e?void 0:t))};\ntransfer tracks: ${Tr(i,((e,t)=>"initSegment"===e?void 0:t))}}`),!function(e,t){const s=Object.keys(e),i=Object.keys(t),r=s.length,n=i.length;return!r||!n||r===n&&!s.some((e=>-1===i.indexOf(e)))}(i,s)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching($s.MEDIA_DETACHING,{}),this.onMediaAttaching($s.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach((e=>{const t=e,s=i[t];if(s){const e=s.buffer;if(e){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=ia.getBuffered(e);i.detectEvictedFragments(t,s,r,null,!0)}const n=ya(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach((([e])=>{e&&this.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),r.removeSourceBuffer(t[s]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&va(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger($s.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach((([e])=>{e&&this.resetBuffer(e)})),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ya(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new fa(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some((e=>!i[e]));n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach((e=>{var s,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=i[e];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[e],g=null!=f&&f.buffer?f:u,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;u||(u=i[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=ar(p,m),y=null==v?void 0:v.replace(ga,"$1");let E=ar(o,l);const S=null==(r=E)?void 0:r.replace(ga,"$1");E&&v&&y!==S&&("audio"===e.slice(0,5)&&(E=nr(E,this.appendSource)),this.log(`switching codec ${p} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=h,this.appendChangeType(e,h,E))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(s=t.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e}),{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,Vs))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>i||null!=t&&t.buffer&&ia.isBuffered(t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,Vs))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:h}=t,d=l.buffering[r],{sn:c,cc:u}=a,f=self.performance.now();d.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;0===g.start&&(g.start=f),p&&0===p.start&&(p.start=f);const m=s.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==m?void 0:m.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=s.video,E=null==y?void 0:y.buffer;if(E&&"initSegment"!==c){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const s=e.end;if(t){const e=t.frag.start;(s>e||s<this.lastVideoAppendEnd||ia.isBuffered(E,e))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const t=e.start+.05*e.duration,s=E.buffered,i=this.currentOp("video");s.length||i?!i&&!ia.isBuffered(E,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const S=(o||a).start,T={label:`append-${r}`,execute:()=>{var e;d.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,S,.1,r,c,u):void 0!==h&&Ms(h)&&this.updateTimestampOffset(t,h,1e-6,r,c,u)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);const t={};this.sourceBuffers.forEach((([e,s])=>{e&&(t[e]=ia.getBuffered(s))})),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger($s.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const s={type:Fs.MEDIA_ERROR,parent:a.type,details:Ns.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},i=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)s.details=Ns.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)s.errorAction=qr(!0);else if(e.name===pa&&0===this.sourceBufferCount)s.errorAction=qr(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${i||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||i)&&(s.fatal=!0)}this.hls.trigger($s.ERROR,s)}};this.log(`queuing "${r}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===Vs?"level":"track"} ${a.level} cc: ${u}`),this.append(T,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger($s.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach((([e])=>{e&&this.append(this.getFlushOp(e,i,r),e)}))}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[Si]?r.push("audiovideo"):(n[yi]&&r.push("audio"),n[Ei]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const e=self.performance.now();s.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:s.stats;this.hls.trigger($s.FRAG_BUFFERED,{frag:s,part:i,stats:t,id:s.type})}),r).catch((e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1}))}onBufferEos(e,t){var s;this.sourceBuffers.forEach((([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}}));const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)}))?i?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger($s.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)}))):(this.tracksEnded(),this.hls.trigger($s.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach((([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen((()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)}))}onError(e,t){if(t.details===Ns.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;Ms(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||null===t)return;if(!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(Ms(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}const o=i.frontBufferFlushThreshold;if(Ms(o)&&o>0){const e=Math.max(i.maxBufferLength,o),t=Math.max(e,n),s=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach((([e,t])=>{if(t){const r=ia.getBuffered(t);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger($s.BACK_BUFFER_REACHED,{bufferEnd:s});const t=this.tracks[e];if(null!=(i=this.details)&&i.live)this.hls.trigger($s.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger($s.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:e})}}}))}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach((([t,i])=>{if(i){const r=ia.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||e>=a&&e<=o)return;this.hls.trigger($s.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}}))}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,i)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return Ms(r)?{duration:r}:null;const n=this.media.duration;return i>(Ms(s.duration)?s.duration:0)&&i>n||!Ms(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;this.media&&i&&"open"===i.readyState&&(i.duration!==e&&(Ms(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Tr(s)}`),this.tracksReady){var i;const e=null==(i=this.transferData)?void 0:i.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach((([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}})),this.hls.trigger($s.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([e])=>{this.executeNext(e)}))}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${Tr(a)}`);try{const e=s.addSourceBuffer(r),i=ya(n),o=[n,e];t[i]=o,a.buffer=e}catch(e){var i;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&("video"===t||"audiovideo"===t)&&Ji(s,"video")&&(i=function(e,t){const s=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)Qi(t[e],"video")||s.push(t[e])}return t&&s.push(t),s.join(",")}(i,s));const r=ar(i,e.levelCodec);return r?"audio"===t.slice(0,5)?nr(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((e,t)=>{const s=t.removedRanges;null!=s&&s.length&&this.hls.trigger($s.BUFFER_FLUSHED,{type:e})}))}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=Ms(i.duration)?i.duration:1/0,l=Ms(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(s,o,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),a.remove(h,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=null==s?void 0:s.buffer;if(!i)throw new ma(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some((([e,t])=>e&&t.updating))}isQueued(){return this.sourceBuffers.some((([e])=>e&&!!this.currentOp(e)))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map((e=>this.appendBlocker(e)));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then((t=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(e){e.forEach((e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;s&&!s.updating&&this.shiftAndExecuteNext(e)}))}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((e,t)=>e+(this.isPending(this.tracks[t])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((e,[t])=>e+(t?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([e])=>e)).filter((e=>!!e))}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach((e=>{s.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},capLevelController:Ea,errorController:class extends Js{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on($s.ERROR,this.onError,this),e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off($s.ERROR,this.onError,this),e.off($s.ERROR,this.onErrorOut,this),e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===Vs?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===s?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if(null!=(s=e.details)&&s.hasKey(t))return!0;const i=e.audioGroups;if(i){return this.hls.allAudioTracks.filter((e=>i.indexOf(e.groupId)>=0)).some((e=>{var s;return null==(s=e.details)?void 0:s.hasKey(t)}))}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case Ns.FRAG_LOAD_ERROR:case Ns.FRAG_LOAD_TIMEOUT:case Ns.KEY_LOAD_ERROR:case Ns.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Ns.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=qr());case Ns.FRAG_GAP:case Ns.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=$r);case Ns.LEVEL_EMPTY_ERROR:case Ns.LEVEL_PARSING_ERROR:{var n;const e=t.parent===Vs?t.level:i.loadLevel;t.details===Ns.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case Ns.LEVEL_LOAD_ERROR:case Ns.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case Ns.AUDIO_TRACK_LOAD_ERROR:case Ns.AUDIO_TRACK_LOAD_TIMEOUT:case Ns.SUBTITLE_LOAD_ERROR:case Ns.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=i.loadLevelObj;if(e&&(r.type===Gs&&e.hasAudioGroup(r.groupId)||r.type===Hs&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=$r,void(t.errorAction.flags=Hr)}return;case Ns.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:$r,flags:Vr});case Ns.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Ns.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Ns.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:$r,flags:Wr});case Ns.BUFFER_ADD_CODEC_ERROR:case Ns.REMUX_ALLOC_ERROR:case Ns.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:i.loadLevel);return;case Ns.INTERNAL_EXCEPTION:case Ns.BUFFER_APPENDING_ERROR:case Ns.BUFFER_FULL_ERROR:case Ns.LEVEL_SWITCH_ERROR:case Ns.BUFFER_STALLED_ERROR:case Ns.BUFFER_SEEK_OVER_HOLE:case Ns.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=qr())}t.type===Fs.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=qr())}getPlaylistRetryOrSwitchAction(e,t){const s=kr(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Or(s,i,Ir(e),e.response))return{action:Ur,flags:Gr,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(e,t);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=kr(Dr(e)?n:r,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(i&&(e.details!==Ns.FRAG_GAP&&i.fragmentError++,!Cr(e))){if(Or(a,o,Ir(e),e.response))return{action:Ur,flags:Gr,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const t=e.details;i.loadError++,t===Ns.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===Ws&&t===Ns.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===Ns.BUFFER_ADD_CODEC_ERROR||t===Ns.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>i.audioCodec!==e)),p="video"===e.sourceBufferName&&(t===Ns.BUFFER_ADD_CODEC_ERROR||t===Ns.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t)),{type:m,groupId:v}=null!=(n=e.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(t===Ns.FRAG_GAP&&f===Vs&&e.frag){const t=h[r].details;if(t){const s=Ar(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(m===Gs&&s.hasAudioGroup(v)||m===Hs&&s.hasSubtitleGroup(v))continue;if(f===Ws&&null!=(a=i.audioGroups)&&a.some((e=>s.hasAudioGroup(e)))||f===qs&&null!=(o=i.subtitleGroups)&&o.some((e=>s.hasSubtitleGroup(e)))||g&&i.audioCodec===s.audioCodec||p&&i.codecSet===s.codecSet||!g&&i.codecSet!==s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:$r,flags:Gr,nextAutoLevel:l}}return{action:$r,flags:Hr}}onErrorOut(e,t){var s;switch(null==(s=t.errorAction)?void 0:s.action){case Nr:break;case $r:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Ns.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Gr:this.switchLevel(e,r);break;case Vr:{const i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(s.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=cr[cr.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Wr:{const t=e.decryptdata;if(t){const i=this.hls.levels,r=i.length;for(let s=r;s--;){var n,a;if(this.variantHasKey(i[s],t))this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(n=i[s].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${ui(t.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${e.error})`),this.hls.removeLevel(s)}const o=e.frag;if(this.hls.levels.length<r)s.resolved=!0;else if(o&&o.type!==Vs){const e=o.decryptdata;e&&!t.matches(e)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===Ns.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=dr(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${i} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(i))}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on($s.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on($s.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off($s.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off($s.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,r=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger($s.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger($s.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!1,preserveManualLevelOnError:!1,certLoadPolicy:{default:Jo},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:Jo},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:hi,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!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,cmcdController:void 0,contentSteeringController:class extends Js{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($s.MANIFEST_PARSED,this.onManifestParsed,this),e.on($s.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($s.MANIFEST_PARSED,this.onManifestParsed,this),e.off($s.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===$r&&s.flags===Hr){const e=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:s,pathwayId:i,type:n}=t.context;s&&e?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&e&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),t.details!==Ns.BUFFER_APPEND_ERROR||t.fatal?s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${Tr(i)} penalized: ${Tr(this.penalizedPathways)}`):s.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach((e=>{i-s[e]>3e5&&delete s[e]}));for(let i=0;i<e.length;i++){const r=e[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Mn(t),this.hls.trigger($s.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(t===Gs&&i[s].hasAudioGroup(e)||t===Hs&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach((e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new zr(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Ta(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new yr({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return h}));t.push(...o),Sa(this.audioTracks,s,a,r),Sa(this.subtitleTracks,i,a,r)}))}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(t);try{i=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger($s.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,s,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,r);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}},interstitialsController:void 0});function el(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(el):Object.keys(e).reduce(((t,s)=>(t[s]=el(e[s]),t)),{}):e}function tl(e,t){const s=e.loader;if(s!==Ko&&s!==Qo)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=Ko,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class sl extends ea{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger($s.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($s.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($s.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;la(s,"playing",this.onMediaPlaying),la(s,"waiting",this.onMediaWaiting),la(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(ha(s,"playing",this.onMediaPlaying),ha(s,"waiting",this.onMediaWaiting),ha(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(h)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger($s.MEDIA_ENDED,{stalled:!1})));if(!ia.getBuffered(n).length)return void(this.nudgeRetry=0);const d=ia.bufferInfo(n,e,0),c=d.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const t=il(this.hls.inFlightFragments,e),s=d.len>2,i=!c||t||c-e>2&&!u.getPartialFragment(e);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(d.len>0)&&!c)return;const t=Math.max(c,d.start||0)-e,s=!(null==f||!f.live)?2*f.targetduration:2,i=nl(e,u);if(t>0&&(t<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m)&&this.hls){var E;if("ended"===(null==(E=this.mediaSource)?void 0:E.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger($s.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}const S=ia.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger($s.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&e>i.end(0)){const s=ia.bufferedInfo(ia.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const s=ia.timeRangesToArray(i),r=ia.bufferedInfo(s,t,0).bufferedIndex;if(r>-1&&r<s.length-1){const t=ia.bufferedInfo(s,e,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===t||t>r)&&n-i<1&&e-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${i} -> ${n} buffered index: ${t}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=nl(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=ia.bufferInfo(this.media,e,0);this.hls.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=nl(s,n);if(h||null!=l&&l.live&&s<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=e.buffered,c=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const e=s.getFragAtPos(t,Vs),r=s.getFragAtPos(i,Vs);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Tr(e)})`);this.warn(i.message),t.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=null==(t=this.hls)?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=ia.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,h=a.len>0&&a.len<1&&i.readyState<3,d=o-n;if(d>0&&(t||h)){if(d>r.maxBufferHole){let t=!1;if(0===n){const e=s.getAppendedFrag(0,Vs);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(il(this.hls.inFlightFragments,o))return 0;let t=!1,i=e.end;for(;i<o;){const e=nl(i,s);if(!e){t=!0;break}i+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,i.currentTime=t,null==e||!e.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),i={type:Fs.MEDIA_ERROR,details:Ns.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?i.part=e:i.frag=e),this.hls.trigger($s.ERROR,i)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=null==t?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:e.len,bufferInfo:e})}}}function il(e,t){const s=rl(e.main);if(s&&s.start<=t)return s;const i=rl(e.audio);return i&&i.start<=t?i:null}function rl(e){if(!e)return null;switch(e.state){case ca.IDLE:case ca.STOPPED:case ca.ENDED:case ca.ERROR:return null}return e.frag}function nl(e,t){return t.getAppendedFrag(e,Vs)||t.getPartialFragment(e)}function al(e,t){let s;try{s=new Event("addtrack")}catch(e){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=e,t.dispatchEvent(s)}function ol(e,t,s,i){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,s){const i=[],r=function(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),t<e[i].startTime)n=i-1;else{if(!(t>e[i].startTime&&r<s))return i;r=i+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(e.cues,t,s);for(let t=0;t<r.length;t++)i&&!i(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function ll(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function hl(e,t,s,i,r){let n=new e(t,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new e(t,s,Tr(r?Qs({type:r},i):i))}return n}const dl=(()=>{const e=ll();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class cl{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger($s.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on($s.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on($s.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($s.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($s.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off($s.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off($s.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($s.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($s.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,!1===(null==(s=t.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&function(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues)for(let s=e.cues.length;s--;)t&&e.cues[s].removeEventListener("enter",t),e.removeCue(e.cues[s]);"disabled"===s&&(e.mode=s)}(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if("metadata"===s.kind&&"id3"===s.label)return al(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=ll();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===Xa.emsg&&!s||!i)continue;const a=ja(r[e].data),o=r[e].pts;let l=o+r[e].duration;l>dl&&(l=dl);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!Ka(s)){this.updateId3CueEnds(o,t);const e=hl(n,o,l,s,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===t&&r.startTime<e&&r.endTime===dl&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===i?e=>e.type===Xa.audioId3&&o:"video"===i?e=>e.type===Xa.emsg&&a:e=>e.type===Xa.audioId3&&o||e.type===Xa.emsg&&a,ol(r,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=ll();if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,h=Object.keys(l);let d=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.cues)&&c.length){const e=Object.keys(d).filter((e=>!h.includes(e)));for(let t=e.length;t--;){var u;const s=e[t],i=null==(u=d[s])?void 0:u.cues;delete d[s],i&&Object.keys(i).forEach((e=>{const t=i[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(e){}}}))}}else d=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==h.length&&Ms(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<h.length;e++){const t=h[e],s=l[t],i=s.startTime,r=d[t],n=(null==r?void 0:r.cues)||{};let o=(null==r?void 0:r.durationKnown)||!1,c=dl;const{duration:u,endDate:f}=s;if(f&&null!==u)c=i+u,o=!0;else if(s.endOnNext&&!o){const e=h.reduce(((e,t)=>{if(t!==s.id){const i=l[t];if(i.class===s.class&&i.startDate>s.startDate&&(!e||s.startDate<e.startDate))return i}return e}),null);e&&(c=e.startTime,o=!0)}const p=Object.keys(s.attr);for(let e=0;e<p.length;e++){const l=p[e];if("ID"===(g=l)||"CLASS"===g||"CUE"===g||"START-DATE"===g||"DURATION"===g||"END-DATE"===g||"END-ON-NEXT"===g)continue;const h=n[l];if(h)!o||null!=r&&r.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=c):h.endTime=c;else if(a){let e=s.attr[l];Yr(l)&&(e=fi(e));const r=hl(a,i,c,{key:l,data:e},Xa.dateRange);r&&(r.id=t,this.id3Track.addCue(r),n[l]=r)}}d[t]={cues:n,dateRange:s,durationKnown:o}}var g}}}class ul{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($s.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off($s.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($s.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($s.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===Ns.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class fl extends Fn{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($s.LEVEL_LOADED,this.onLevelLoaded,this),e.on($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($s.FRAG_BUFFERED,this.onFragBuffered,this),e.on($s.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($s.LEVEL_LOADED,this.onLevelLoaded,this),e.off($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($s.FRAG_BUFFERED,this.onFragBuffered,this),e.off($s.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{const t=e.attrs;let{audioCodec:h,videoCodec:d}=e;h&&(e.audioCodec=h=nr(h,s)||void 0),d&&(d=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const s=t[e].split(".");s.length>2&&"avc1"===s[0]&&(t[e]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}(d));const{width:c,height:u,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!d),l||(l=!!h),g||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:p,"FRAME-RATE":m,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":S}=t,T=`${`${y||"."}-`}${e.bitrate}-${E}-${m}-${p}-${S}-${v}`;if(r[T])if(r[T].uri===e.url||e.attrs["PATHWAY-ID"])r[T].addGroupId("audio",t.AUDIO),r[T].addGroupId("text",t.SUBTITLES);else{const t=n[T]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=this.createLevel(e);r[T]=s,i.push(s)}else{const t=this.createLevel(e);r[T]=t,n[T]=1,i.push(t)}})),this.filterAndSortMediaOptions(i,t,a,o,l)}createLevel(e){const t=new yr(e),s=e.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(e.message),t.supportedResult=li.getUnsupportedResult(e,[])}return t}isAudioSupported(e){return Ji(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Ji(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let a=[],o=[],l=e;const h=(null==(n=t.stats)?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter((({videoCodec:e,videoRange:t,width:s,height:i})=>{return(!!e||!(!s||!i))&&(!!(r=t)&&ur.indexOf(r)>-1);var r}))),0===l.length)return Promise.resolve().then((()=>{if(this.hls){let e="no level with compatible codecs found in manifest",s=e;t.levels.length&&(s=`one or more CODECS in variant not supported: ${Tr(t.levels.map((e=>e.attrs.CODECS)).filter(((e,t,s)=>s.indexOf(e)===t)))}`,this.warn(s),e+=` (${s})`);const i=new Error(e);this.hls.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:s})}})),void(h.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter((e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),gl(a)),t.subtitles&&(o=t.subtitles,gl(o));const d=l.slice(0);l.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return ur.indexOf(e.videoRange)-ur.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=tr(e.videoCodec),i=tr(t.videoCodec);if(s!==i)return i-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=sr(e.codecSet),i=sr(t.codecSet);if(s!==i)return i-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let c=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length))for(let e=0;e<d.length;e++)if(d[e].pathwayId===l[0].pathwayId){c=d[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===c){var u;this._firstLevel=e;const t=c.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=r&&!i,g=this.hls.config,p=!(!g.audioStreamController||!g.audioTrackController),m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:p&&!f&&a.some((e=>!!e.url))};h.end=performance.now(),this.hls.trigger($s.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),i=e<0;if(this.hls.trigger($s.ERROR,{type:Fs.OTHER_ERROR,details:Ns.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:s,reason:s.message}),i)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger($s.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter((e=>-1!==t.indexOf(e)));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===Us&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===Vs){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(i,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${s}`),this.hls.trigger($s.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter(((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));Mn(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger($s.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger($s.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function gl(e){const t={};e.forEach((e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++}))}const pl="1.6.15",ml={};let vl=0;class yl{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=vl++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger($s.ERROR,{type:Fs.OTHER_ERROR,details:Ns.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===$s.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Ra,this.observer.on($s.FRAG_DECRYPTED,n),this.observer.on($s.ERROR,n);const a=hr(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=ml[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return ml[e]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=ml[pl];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return ml[pl]=i,i}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Tr(r)})}catch(i){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Go(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Go(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=vl++;const t=this.hls.config,s=hr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:Tr(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=ml[e||pl];if(t&&1==t.clientCount--){const{worker:s,objectURL:i}=t;delete ml[e||pl],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,p=r.decryptdata,m=this.frag,v=!(m&&r.cc===m.cc),y=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,S=this.part?l.part-this.part.index:-1,T=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),_=!y&&(1===E||0===E&&(1===S||T&&S<=0)),L=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!S&&_||(n.stats.parsing.start=L);const b=!(m&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),R=new qo(v,_,o,y,g,b);if(!_||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Vs?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${_}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${b}`);const e=new Wo(s,i,t,a,h);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,p,l,R);Vo(t)?t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);Vo(t)?t.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger($s.ERROR,{type:Fs.MEDIA_ERROR,details:Ns.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function El(){return self.SourceBuffer||self.WebKitSourceBuffer}function Sl(){if(!di())return!1;const e=El();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Tl extends ua{constructor(e,t,s){super(e,t,s,"stream-controller",Vs),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!Ms(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const s=this.getFwdBufferInfoAtPos(e,t,Vs,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on($s.MANIFEST_PARSED,this.onManifestParsed,this),e.on($s.LEVEL_LOADING,this.onLevelLoading,this),e.on($s.LEVEL_LOADED,this.onLevelLoaded,this),e.on($s.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on($s.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on($s.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on($s.BUFFER_CREATED,this.onBufferCreated,this),e.on($s.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($s.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off($s.MANIFEST_PARSED,this.onManifestParsed,this),e.off($s.LEVEL_LOADED,this.onLevelLoaded,this),e.off($s.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off($s.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off($s.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off($s.BUFFER_CREATED,this.onBufferCreated,this),e.off($s.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off($s.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($s.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=ca.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=ca.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ca.WAITING_LEVEL:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=ca.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=ca.IDLE;break}break}case ca.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===ca.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(null===t||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger($s.BUFFER_EOS,e),void(this.state=ca.ENDED)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===ca.WAITING_LEVEL||this.waitForLive(n))return this.level=r,this.state=ca.WAITING_LEVEL,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&_i(u)&&this.fragmentTracker.getState(u)!==Un){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?yi:Ei,t=(e===Ei?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Vs)}u=this.getNextFragmentLoopLoading(u,l,a,Vs,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Nn||i===Bn?_i(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Vs)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,i=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ca.KEY_LOADING:case ca.FRAG_LOADING:case ca.FRAG_LOADING_WAITING_RETRY:case ca.PARSING:case ca.PARSED:this.state=ca.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;la(s,"playing",this.onMediaPlaying),la(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(ha(s,"playing",this.onMediaPlaying),ha(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger($s.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let e=0;e<t.levels.length;e++){const r=t.levels[e].audioCodec;r&&(s=s||-1!==r.indexOf("mp4a.40.2"),i=i||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var e;const t=El();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==ca.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=ca.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==ca.FRAG_LOADING&&this.state!==ca.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,d),this.hls.trigger($s.LEVEL_UPDATED,{details:a,level:n}),this.state===ca.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=ca.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=ia.bufferInfo(s,i,0);if(null==(l=e.buffered)||!l.length)return void(s.currentTime=i);if(e.start<=r)return void(s.currentTime=i);const{nextStart:t}=ia.bufferedInfo(e.buffered,r,0);t&&(s.currentTime=t)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new yl(this.hls,Vs,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,p=new ta(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,p,m)}onAudioTrackSwitching(e,t){const s=this.hls,i=0!==this.altAudio;if(br(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once($s.BUFFER_FLUSHED,(()=>{this.hls&&this.hls.trigger($s.AUDIO_TRACK_SWITCHED,t)})),void s.trigger($s.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger($s.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=br(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const e in s){const t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){const t=s[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===Vs;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===ca.PARSED&&(this.state=ca.IDLE));const e=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),_i(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&ia.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=ca.ERROR;else switch(t.details){case Ns.FRAG_GAP:case Ns.FRAG_PARSING_ERROR:case Ns.FRAG_DECRYPT_ERROR:case Ns.FRAG_LOAD_ERROR:case Ns.FRAG_LOAD_TIMEOUT:case Ns.KEY_LOAD_ERROR:case Ns.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Vs,t);break;case Ns.LEVEL_LOAD_ERROR:case Ns.LEVEL_LOAD_TIMEOUT:case Ns.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==ca.WAITING_LEVEL||(null==(s=t.context)?void 0:s.type)!==Us||(this.state=ca.IDLE);break;case Ns.BUFFER_ADD_CODEC_ERROR:case Ns.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Ns.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Ns.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=ca.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==yi||!this.altAudio){const e=(t===Ei?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,Vs),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=ia.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((e=>{const{hls:s}=this,i=null==e?void 0:e.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=ca.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger($s.FRAG_LOADED,e),i.bitrateTest=!1})).catch((t=>{this.state!==ca.STOPPED&&this.state!==ca.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:h,text:d,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=ca.PARSING,u){const e=u.tracks;if(e){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,i,r),s.trigger($s.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:t,tracks:e})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(Ms(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:e},s.trigger($s.INIT_PTS_FOUND,{frag:a,id:t,initPTS:i,timescale:n,trackId:e})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,s=!e||a.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:i,startDTS:n,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:e,endPTS:i,startDTS:n,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,i,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,e,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,t||s)}else{if(!t&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[yi]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(yi,e,t,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};s.trigger($s.FRAG_PARSING_METADATA,e)}if(f&&d){const e={id:t,frag:a,details:f,samples:d.samples};s.trigger($s.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${_i(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==ca.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=t;if(r){const s=e.audioCodec;let i=ar(r.codec,s);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=Vs,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=Vs;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger($s.BUFFER_CODECS,t),!this.hls)return;o.forEach((e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger($s.BUFFER_APPENDING,{type:e,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Vs)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=ca.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(ia.isBuffered(e,s)?t=this.getAppendedFrag(s):ia.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,s=t.level;e&&t.sn===e.sn&&e.level===s||(this.fragPlaying=t,this.hls.trigger($s.FRAG_CHANGED,{frag:t}),e&&e.level===s||this.hls.trigger($s.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return Ms(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(Ms(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?Ar(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const i=e+1e3*(t-s.start);return new Date(i)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class _l extends Js{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=Ns.KEY_LOAD_ERROR,s,i,r){return new Zn({type:Fs.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var s,i;const r=e.decryptdata;if(!r){const s=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,Ns.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,Ns.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=Ll(r);let o=this.keyIdToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(i=o)&&i.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then((t=>{const{keyInfo:s}=t;return r.key=s.decryptdata.key,{frag:e,keyInfo:s}}))}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+ui(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,Ns.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){const s=function(e){const t=[];return Hi(e,(e=>t.push(e.subarray(8,24)))),t}(t.initSegment.data);if(s.length){let t=s[0];t.some((e=>0!==e))?(this.log(`Using keyId found in init segment ${ui(t)}`),an.setKeyIdForUri(e.decryptdata.uri,t)):(t=an.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ui(t)}`)),e.decryptdata.keyId=t}}if(!e.decryptdata.keyId&&!_i(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then((t=>(e.mediaKeySessionContext=t,s)))).catch((s=>{throw e.keyLoadPromise=null,"data"in s&&(s.data.frag=t),s}))}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=new(0,s.loader)(s);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{const{frag:a,keyInfo:o}=s,l=Ll(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,Ns.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,Ns.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),i,Qs({url:a.url,data:void 0},e)))},onTimeout:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,Ns.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(e,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,Ns.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,h)}))}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=Ll(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function Ll(e){return e.uri}function bl(e){const{type:t}=e;switch(t){case Gs:return Ws;case Hs:return qs;default:return Vs}}function Rl(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}class Al{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on($s.MANIFEST_LOADING,this.onManifestLoading,this),e.on($s.LEVEL_LOADING,this.onLevelLoading,this),e.on($s.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on($s.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on($s.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off($s.MANIFEST_LOADING,this.onManifestLoading,this),e.off($s.LEVEL_LOADING,this.onLevelLoading,this),e.off($s.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off($s.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off($s.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=new(s||i)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Bs,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Us,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Gs,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Hs,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[Us];if(s){const e=s.context;e&&!t.levels.some((t=>t===e.levelOrTrack))&&(s.abort(),delete this.loaders[Us])}}load(e){var t;const s=this.hls.config;let i,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,s=r.context;if(s&&s.levelOrTrack===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(i=e.type===Bs?s.manifestLoadPolicy.default:Ys({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Ms(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===Us&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Gs&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Hs&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);i=Ys({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;t.parsing.start=performance.now(),un.isMediaPlaylist(n)||s.type!==Bs?this.handleTrackOrLevelPlaylist(e,t,s,i||null,r):this.handleMasterPlaylist(e,t,s,i)},onError:(e,t,s,i)=>{this.handleNetworkError(t,s,!1,e,i)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,a=Rl(e,s),o=un.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,o.playlistParsingError,i,t);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,h.forEach((e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];Ji(a,"audio",s)?(e.audioCodec=i=i?`${i},${a}`:a,Xi.audio[i.substring(0,4)]=2,t.splice(n,1)):Ji(a,"video",s)&&(e.videoCodec=r=r?`${r},${a}`:a,Xi.video[r.substring(0,4)]=2,t.splice(n,1))}}}));const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=un.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new zr({}),bitrate:0,url:""}))}r.trigger($s.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=Rl(e,s),d=Ms(o)?o:Ms(a)?a:0,c=bl(s),u=un.parseLevelPlaylist(e.data,h,d,c,0,this.variableList);if(l===Bs){const e={attrs:new zr({}),bitrate:0,details:u,name:"",url:h};u.requestScheduled=t.loading.start+In(u,0),n.trigger($s.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger($s.ERROR,{type:Fs.NETWORK_ERROR,details:Ns.MANIFEST_PARSING_ERROR,fatal:t.type===Bs,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Us?n+=`: ${e.level} id: ${e.id}`:e.type!==Gs&&e.type!==Hs||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=Ns.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Bs:o=s?Ns.MANIFEST_LOAD_TIMEOUT:Ns.MANIFEST_LOAD_ERROR,l=!0;break;case Us:o=s?Ns.LEVEL_LOAD_TIMEOUT:Ns.LEVEL_LOAD_ERROR,l=!1;break;case Gs:o=s?Ns.AUDIO_TRACK_LOAD_TIMEOUT:Ns.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Hs:o=s?Ns.SUBTITLE_TRACK_LOAD_TIMEOUT:Ns.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const d={type:Fs.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};if(i){const s=(null==t?void 0:t.url)||e.url;d.response=Qs({url:s,data:void 0},i)}this.hls.trigger($s.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:d,groupId:c,deliveryDirectives:u}=i,f=Rl(t,i),g=bl(i);let p="number"==typeof i.level&&g===Vs?l:void 0;const m=e.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger($s.ERROR,{type:Fs.NETWORK_ERROR,details:Ns.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:i,level:p,parent:g,networkDetails:r,stats:s});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Bs:case Us:if(p)if(h){if(h!==a.levels[p]){const e=a.levels.indexOf(h);e>-1&&(p=e)}}else p=0;a.trigger($s.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:p||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===Bs});break;case Gs:a.trigger($s.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case Hs:a.trigger($s.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u})}else{const n=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger($s.ERROR,{type:Fs.NETWORK_ERROR,details:Ns.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:i,level:p,parent:g,networkDetails:r,stats:s})}}}const Pl={supported:!1,smooth:!1,powerEfficient:!1},wl={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Il(e,t,s,i={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!s)return Promise.resolve(wl);const n=[],a=function(e){var t;const s=null==(t=e.videoCodec)?void 0:t.split(","),i=Cl(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map((e=>{const t={contentType:er(lr(e),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t})):[]}(e),o=a.length,l=function(e,t,s){var i;const r=null==(i=e.audioCodec)?void 0:i.split(","),n=Cl(e);if(r&&e.audioGroups)return e.audioGroups.reduce(((e,i)=>{var a;const o=i?null==(a=t.groups[i])?void 0:a.tracks:null;return o?o.reduce(((e,t)=>{if(t.groupId===i){const i=parseFloat(t.channels||"");r.forEach((t=>{const r={contentType:er(t,"audio"),bitrate:s?Dl(t,n):n};i&&(r.channels=""+i),e.push(r)}))}return e}),e):e}),[]);return[]}(e,t,o>0),h=l.length;for(let e=o||1*h||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),h){t.audio=l[e%h];const s=t.audio.bitrate;t.video&&s&&(t.video.bitrate-=s)}n.push(t)}if(r){const e=navigator.userAgent;if(r.split(",").some((e=>qi(e)))&&Yi())return Promise.resolve(function(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Pl],error:e}}(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map((e=>{const t=function(e){let t="";const{audio:s,video:i}=e;if(i){t+=`${dr(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(s){t+=`${i?"_":""}${dr(s.contentType)}_c${s.channels}`}return t}(e);return i[t]||(i[t]=s.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:n,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e})))}function Dl(e,t){if(t<=1)return 1;let s=128e3;return"ec-3"===e?s=768e3:"ac-3"===e&&(s=64e4),Math.min(t/2,s)}function Cl(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}class kl{static get version(){return pl}static isMSESupported(){return Sl()}static isSupported(){return function(){if(!Sl())return!1;const e=di();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(er(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(er(t,"audio")))))}()}static getMediaSource(){return di()}static get Events(){return $s}static get MetadataSchema(){return Xa}static get ErrorTypes(){return Fs}static get ErrorDetails(){return Ns}static get DefaultConfig(){return kl.defaultConfig?kl.defaultConfig:Zo}static set DefaultConfig(e){kl.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ra,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,s){const i=ti();if("object"==typeof console&&!0===e||"object"==typeof e){const r=["debug","log","info","warn","error"];r.forEach((t=>{i[t]=si(t,e,s)}));try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch(e){return ti()}r.forEach((t=>{ii[t]=si(t,e)}))}else Ys(ii,i);return i}(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=function(e,t,s){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");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=el(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach((s=>{const r=`${e}Loading${s}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=i[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Tr(t[n])}`)})),Qs(Qs({},i),t)}(kl.DefaultConfig,e,t);this.userConfig=e,s.progressive&&tl(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=s,l=new a(this),h=this.abrController=new i(this),d=new Gn(this),c=s.interstitialsController,u=c?this.interstitialsController=new c(this,kl):null,f=this.bufferController=new r(this,d),g=this.capLevelController=new n(this),p=new o(this),m=new Al(this),v=s.contentSteeringController,y=v?new v(this):null,E=this.levelController=new fl(this,y),S=new cl(this),T=new _l(this.config,this.logger),_=this.streamController=new Tl(this,d,T),L=this.gapController=new sl(this,d);g.setStreamController(_),p.setStreamController(_);const b=[m,E,_];u&&b.splice(1,0,u),y&&b.splice(1,0,y),this.networkControllers=b;const R=[h,f,L,g,p,S,d];this.audioTrackController=this.createController(s.audioTrackController,b);const A=s.audioStreamController;A&&b.push(this.audioStreamController=new A(this,d,T)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);const P=s.subtitleStreamController;P&&b.push(this.subtititleStreamController=new P(this,d,T)),this.createController(s.timelineController,R),T.emeController=this.emeController=this.createController(s.emeController,R),this.cmcdController=this.createController(s.cmcdController,R),this.latencyController=this.createController(ul,R),this.coreComponents=R,b.push(l);const w=l.onErrorOut;"function"==typeof w&&this.on($s.ERROR,w,l),this.on($s.MANIFEST_LOADED,m.onManifestLoaded,m)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const s=e===$s.ERROR;this.trigger($s.ERROR,{type:Fs.OTHER_ERROR,details:Ns.INTERNAL_EXCEPTION,fatal:s,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger($s.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger($s.ERROR,{type:Fs.OTHER_ERROR,details:Ns.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger($s.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger($s.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger($s.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=mi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger($s.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((e=>{e.resumeBuffering&&e.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((e=>{e.pauseBuffering&&e.pauseBuffering()})))}get inFlightFragments(){const e={[Vs]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Ws]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[qs]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?s:3&s|8).toString(16)}))}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return cr.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let t=i;t--;){const i=e[t].attrs["HDCP-LEVEL"];if(i&&i<=s)return t}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Il(e,Lr(t),navigator.mediaCapabilities)}}kl.defaultConfig=void 0;li.KeySystemFormats,li.KeySystems,li.SubtitleStreamController,li.TimelineController,li.requestMediaKeySystemAccess;const Ml={maxBufferLength:12},xl={maxBufferLength:40};class Ol extends kl{static get P2PEvents(){return ks.Events}static get P2pEngine(){return ks}constructor(e={}){let t=e.p2pConfig||{};const s=!1===t.live?xl:Ml;let i=JSON.parse(JSON.stringify(s));i.maxBufferSize=0;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},ks.isSupported()&&(this._p2pEngine=new ks({...t,hlsjsInstance:this}),this._p2pEngine.on(ks.Events.RESTART_P2P,this._restartEvent)),this.on(kl.Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(ks.Events.RESTART_P2P,this._restartEvent),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.removeAllListeners(ks.Events.RESTART_P2P),this._p2pEngine.once(ks.Events.RESTART_P2P,(()=>{this.disableP2P()})))}}Ol.engineVersion=ks.version,Ol.protocolVersion=ks.protocolVersion,Ol.WEBRTC_SUPPORT=ks.isSupported();const Fl=Ol})(),i=i.default})()));
|