stormcloud-video-player 0.4.0 → 0.4.1

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.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StormcloudVP={})}(this,function(e){"use strict";function t(e,t){this.v=e,this.k=t}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function i(e){if(Array.isArray(e))return e}function n(e,t,r){return t=c(t),g(e,h()?Reflect.construct(t,r||[],c(e).constructor):t.apply(e,r))}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,T(i.key),i)}}function o(e,t,r){return t&&s(e.prototype,t),r&&s(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(e,t,r){return(t=T(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(){return u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var i=y(e,t);if(i){var n=Object.getOwnPropertyDescriptor(i,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}},u.apply(null,arguments)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function d(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&p(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(h=function(){return!!e})()}function f(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function v(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function g(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function m(e,t){return i(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var i,n,a,s,o=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;l=!1}else for(;!(l=(i=a.call(r)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}(e,t)||b(e,t)||v()}function y(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=c(e)););return e}function E(e,t,r,i){var n=u(c(1&i?e.prototype:e),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}function k(e){return function(e){if(Array.isArray(e))return r(e)}(e)||f(e)||b(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function T(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");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+""}function S(e){return S="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},S(e)}function b(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}function A(e){var r,i;function n(r,i){try{var s=e[r](i),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var i="return"===r?"return":"next";if(!o.k||t.done)return n(i,t);t=e[i](t).value}a(s.done?"return":"normal",t)},function(e){n("throw",e)})}catch(e){a("throw",e)}}function a(e,t){switch(e){case"return":r.resolve({value:t,done:!0});break;case"throw":r.reject(t);break;default:r.resolve({value:t,done:!1})}(r=r.next)?n(r.key,r.arg):i=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};i?i=i.next=o:(r=i=o,n(e,t))})},"function"!=typeof e.return&&(this.return=void 0)}function L(e){var t="function"==typeof Map?new Map:void 0;return L=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&p(n,r.prototype),n}(e,arguments,c(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),p(r,e)},L(e)}A.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},A.prototype.next=function(e){return this._invoke("next",e)},A.prototype.throw=function(e){return this._invoke("throw",e)},A.prototype.return=function(e){return this._invoke("return",e)};var I=function(e,t){return I=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},I(e,t)};function R(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}I(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var w=function(){return w=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},w.apply(this,arguments)};function P(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function x(e,t,r,i){return new(r||(r=Promise))(function(n,a){function s(e){try{l(i.next(e))}catch(e){a(e)}}function o(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((i=i.apply(e,t||[])).next())})}function D(e,t){var r,i,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(r=1,i&&(n=2&o[0]?i.return:o[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,o[1])).done)return n;switch(i=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,i=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){a.label=o[1];break}if(6===o[0]&&a.label<n[1]){a.label=n[1],n=o;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(o);break}n[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],i=0}finally{r=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function C(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function _(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,a=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=a.next()).done;)s.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return s}function M(e,t,r){if(r||2===arguments.length)for(var i,n=0,a=t.length;n<a;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}Object.create;"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function O(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var F,N={exports:{}},U={};var B,G={exports:{}},H={};function V(){if(B)return H;B=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),s=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),c=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),h=Symbol.iterator;var f={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,g={};function p(e,t,r){this.props=e,this.context=t,this.refs=g,this.updater=r||f}function m(){}function y(e,t,r){this.props=e,this.context=t,this.refs=g,this.updater=r||f}p.prototype.isReactComponent={},p.prototype.setState=function(e,t){if("object"!==S(e)&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},p.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},m.prototype=p.prototype;var E=y.prototype=new m;E.constructor=y,v(E,p.prototype),E.isPureReactComponent=!0;var k=Array.isArray;function T(){}var b={H:null,A:null,T:null,S:null},A=Object.prototype.hasOwnProperty;function L(t,r,i){var n=i.ref;return{$$typeof:e,type:t,key:r,ref:void 0!==n?n:null,props:i}}function I(t){return"object"===S(t)&&null!==t&&t.$$typeof===e}var R=/\/+/g;function w(e,t){return"object"===S(e)&&null!==e&&null!=e.key?(r=""+e.key,i={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,function(e){return i[e]})):t.toString(36);var r,i}function P(r,i,n,a,s){var o=S(r);"undefined"!==o&&"boolean"!==o||(r=null);var l,u,d=!1;if(null===r)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(r.$$typeof){case e:case t:d=!0;break;case c:return P((d=r._init)(r._payload),i,n,a,s)}}if(d)return s=s(r),d=""===a?"."+w(r,0):a,k(s)?(n="",null!=d&&(n=d.replace(R,"$&/")+"/"),P(s,i,n,"",function(e){return e})):null!=s&&(I(s)&&(l=s,u=n+(null==s.key||r&&r.key===s.key?"":(""+s.key).replace(R,"$&/")+"/")+d,s=L(l.type,u,l.props)),i.push(s)),1;d=0;var f,v=""===a?".":a+":";if(k(r))for(var g=0;g<r.length;g++)d+=P(a=r[g],i,n,o=v+w(a,g),s);else if("function"==typeof(g=null===(f=r)||"object"!==S(f)?null:"function"==typeof(f=h&&f[h]||f["@@iterator"])?f:null))for(r=g.call(r),g=0;!(a=r.next()).done;)d+=P(a=a.value,i,n,o=v+w(a,g++),s);else if("object"===o){if("function"==typeof r.then)return P(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(T,T):(e.status="pending",e.then(function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)},function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(r),i,n,a,s);throw i=String(r),Error("Objects are not valid as a React child (found: "+("[object Object]"===i?"object with keys {"+Object.keys(r).join(", ")+"}":i)+"). If you meant to render a collection of children, use an array instead.")}return d}function x(e,t,r){if(null==e)return e;var i=[],n=0;return P(e,i,"","",function(e){return t.call(r,e,n++)}),i}function D(e){if(-1===e._status){var t=e._result;(t=t()).then(function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)},function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)}),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var C="function"==typeof reportError?reportError:function(e){if("object"===("undefined"==typeof window?"undefined":S(window))&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"===S(e)&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"===("undefined"==typeof process?"undefined":S(process))&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},_={map:x,forEach:function(e,t,r){x(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return x(e,function(){t++}),t},toArray:function(e){return x(e,function(e){return e})||[]},only:function(e){if(!I(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};return H.Activity=d,H.Children=_,H.Component=p,H.Fragment=r,H.Profiler=n,H.PureComponent=y,H.StrictMode=i,H.Suspense=l,H.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=b,H.__COMPILER_RUNTIME={__proto__:null,c:function(e){return b.H.useMemoCache(e)}},H.cache=function(e){return function(){return e.apply(null,arguments)}},H.cacheSignal=function(){return null},H.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var i=v({},e.props),n=e.key;if(null!=t)for(a in void 0!==t.key&&(n=""+t.key),t)!A.call(t,a)||"key"===a||"__self"===a||"__source"===a||"ref"===a&&void 0===t.ref||(i[a]=t[a]);var a=arguments.length-2;if(1===a)i.children=r;else if(1<a){for(var s=Array(a),o=0;o<a;o++)s[o]=arguments[o+2];i.children=s}return L(e.type,n,i)},H.createContext=function(e){return(e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider=e,e.Consumer={$$typeof:a,_context:e},e},H.createElement=function(e,t,r){var i,n={},a=null;if(null!=t)for(i in void 0!==t.key&&(a=""+t.key),t)A.call(t,i)&&"key"!==i&&"__self"!==i&&"__source"!==i&&(n[i]=t[i]);var s=arguments.length-2;if(1===s)n.children=r;else if(1<s){for(var o=Array(s),l=0;l<s;l++)o[l]=arguments[l+2];n.children=o}if(e&&e.defaultProps)for(i in s=e.defaultProps)void 0===n[i]&&(n[i]=s[i]);return L(e,a,n)},H.createRef=function(){return{current:null}},H.forwardRef=function(e){return{$$typeof:o,render:e}},H.isValidElement=I,H.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:D}},H.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},H.startTransition=function(e){var t=b.T,r={};b.T=r;try{var i=e(),n=b.S;null!==n&&n(r,i),"object"===S(i)&&null!==i&&"function"==typeof i.then&&i.then(T,C)}catch(e){C(e)}finally{null!==t&&null!==r.types&&(t.types=r.types),b.T=t}},H.unstable_useCacheRefresh=function(){return b.H.useCacheRefresh()},H.use=function(e){return b.H.use(e)},H.useActionState=function(e,t,r){return b.H.useActionState(e,t,r)},H.useCallback=function(e,t){return b.H.useCallback(e,t)},H.useContext=function(e){return b.H.useContext(e)},H.useDebugValue=function(){},H.useDeferredValue=function(e,t){return b.H.useDeferredValue(e,t)},H.useEffect=function(e,t){return b.H.useEffect(e,t)},H.useEffectEvent=function(e){return b.H.useEffectEvent(e)},H.useId=function(){return b.H.useId()},H.useImperativeHandle=function(e,t,r){return b.H.useImperativeHandle(e,t,r)},H.useInsertionEffect=function(e,t){return b.H.useInsertionEffect(e,t)},H.useLayoutEffect=function(e,t){return b.H.useLayoutEffect(e,t)},H.useMemo=function(e,t){return b.H.useMemo(e,t)},H.useOptimistic=function(e,t){return b.H.useOptimistic(e,t)},H.useReducer=function(e,t,r){return b.H.useReducer(e,t,r)},H.useRef=function(e){return b.H.useRef(e)},H.useState=function(e){return b.H.useState(e)},H.useSyncExternalStore=function(e,t,r){return b.H.useSyncExternalStore(e,t,r)},H.useTransition=function(){return b.H.useTransition()},H.version="19.2.0",H}var K;G.exports;function j(){return K||(K=1,G.exports=V()),G.exports}var Y;N.exports;var W=(Y||(Y=1,N.exports=function(){if(F)return U;F=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(t,r,i){var n=null;if(void 0!==i&&(n=""+i),void 0!==r.key&&(n=""+r.key),"key"in r)for(var a in i={},r)"key"!==a&&(i[a]=r[a]);else i=r;return r=i.ref,{$$typeof:e,type:t,key:n,ref:void 0!==r?r:null,props:i}}return U.Fragment=t,U.jsx=r,U.jsxs=r,U}()),N.exports),q=j(),z=O(q),X=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Q=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=$},$=Number.MAX_SAFE_INTEGER||9007199254740991,J=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}({}),Z=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}({}),ee=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}({}),te="manifest",re="level",ie="audioTrack",ne="subtitleTrack",ae="main",se="audio",oe="subtitle",le=function(){return o(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;a(this,e),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=i},[{key:"sample",value:function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}},{key:"getTotalWeight",value:function(){return this.totalWeight_}},{key:"getEstimate",value:function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}])}(),ue=function(){return o(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;a(this,e),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_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new le(t),this.fast_=new le(r),this.defaultTTFB_=n,this.ttfb_=new le(t)},[{key:"update",value:function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new le(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new le(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new le(e,n.getEstimate(),n.getTotalWeight()))}},{key:"sample",value:function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}},{key:"sampleTTFB",value:function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}},{key:"canEstimate",value:function(){return this.fast_.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"getEstimateTTFB",value:function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{key:"defaultEstimate",get:function(){return this.defaultEstimate_}},{key:"destroy",value:function(){}}])}();function ce(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=S(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=S(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==S(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function de(){return de=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},de.apply(null,arguments)}function he(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function fe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?he(Object(r),!0).forEach(function(t){ce(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):he(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var ve=o(function e(t,r){a(this,e),this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="[".concat(t,"]:");this.trace=ge,this.debug=r.debug.bind(null,i),this.log=r.log.bind(null,i),this.warn=r.warn.bind(null,i),this.info=r.info.bind(null,i),this.error=r.error.bind(null,i)}),ge=function(){},pe={trace:ge,debug:ge,log:ge,warn:ge,info:ge,error:ge};function me(){return de({},pe)}function ye(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):ge}(e,r)}var Ee=me();var ke=Ee;function Te(){if("undefined"!=typeof self)return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0]||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Se(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some(function(e){return-1===i.indexOf(e)})}function be(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if("undefined"!=typeof TextDecoder){var r=new TextDecoder("utf-8").decode(e);if(t){var i=r.indexOf("\0");return-1!==i?r.substring(0,i):r}return r.replace(/\0/g,"")}for(var n,a,s,o=e.length,l="",u=0;u<o;){if(0===(n=e[u++])&&t)return l;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:a=e[u++],l+=String.fromCharCode((31&n)<<6|63&a);break;case 14:a=e[u++],s=e[u++],l+=String.fromCharCode((15&n)<<12|(63&a)<<6|63&s)}}return l}function Ae(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Le(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Ie(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Re,we={exports:{}};var Pe=(Re||(Re=1,function(e){var t,r,i,n,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):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=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(u.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var c=o.path,d=c.substring(0,c.lastIndexOf("/")+1)+s.path;u.path=a.normalizePath(d)}else u.path=o.path,s.params||(u.params=o.params,s.query||(u.query=o.query));return null===u.path&&(u.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(we)),we.exports),xe=o(function e(){a(this,e),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}}),De="audio",Ce="video",_e="audiovideo",Me=function(){return o(function e(t){var r,i,n;a(this,e),this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,(n=Ue(r=this,i="stats"))&&(n.enumerable=!0,Object.defineProperty(r,i,n))},[{key:"setByteRange",value:function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}},{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){return null===this._streams&&(this._streams=l(l(l({},De,null),Ce,null),_e,null)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new xe),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Pe.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}},{key:"clearElementaryStreamInfo",value:function(){var e=this.elementaryStreams;e[De]=null,e[Ce]=null,e[_e]=null}}])}();function Oe(e){return"initSegment"!==e.sn}var Fe=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r]))._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=e,i}return d(t,e),o(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],r=this.byteRange[1];if(X(t)&&X(r))return r-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){var e,t=this.levelkeys;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){var r=Object.keys(t);if(1===r.length){var i=this._decryptdata=t[r[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=X(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,r=Object.keys(this.levelkeys),i=r.length;if(i>1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){X(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return Oe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}},{key:"addStart",value:function(e){this.setStart(this.start+e)}},{key:"setStart",value:function(e){this.start=e,this._ref&&(this._ref.start=e)}},{key:"setDuration",value:function(e){this.duration=e,this._ref&&(this._ref.duration=e)}},{key:"setKeyFormat",value:function(e){var t=this.levelkeys;if(t){var r,i=t[e];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}},{key:"abortRequests",value:function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}},{key:"setElementaryStreamInfo",value:function(e,t,r,i,n){var a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}}}])}(Me),Ne=function(e){function t(e,r,i,s,o){var l;a(this,t),(l=n(this,t,[i])).fragOffset=0,l.duration=0,l.gap=!1,l.independent=!1,l.relurl=void 0,l.fragment=void 0,l.index=void 0,l.duration=e.decimalFloatingPoint("DURATION"),l.gap=e.bool("GAP"),l.independent=e.bool("INDEPENDENT"),l.relurl=e.enumeratedString("URI"),l.fragment=r,l.index=s;var u=e.enumeratedString("BYTERANGE");return u&&l.setByteRange(u,o),o&&(l.fragOffset=o.fragOffset+o.duration),l}return d(t,e),o(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}])}(Me);function Ue(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||Ue(r,t)}}var Be=Math.pow(2,32)-1,Ge=[].push,He={video:1,audio:2,id3:3,text:4};function Ve(e){return String.fromCharCode.apply(null,e)}function Ke(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function je(e,t){var r=We(e,t);return r<0?4294967296+r:r}function Ye(e,t){var r=je(e,t);return r*=Math.pow(2,32),r+=je(e,t+4)}function We(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function qe(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,n=0;n<i;){var a=je(e,n),s=a>1?n+a:i;if(Ve(e.subarray(n+4,n+8))===t[0])if(1===t.length)r.push(e.subarray(n+8,s));else{var o=qe(e.subarray(n+8,s),t.slice(1));o.length&&Ge.apply(r,o)}n=s}return r}function ze(e){var t=[],r=e[0],i=8,n=je(e,i);i+=4;var a=0,s=0;0===r?(a=je(e,i),s=je(e,i+4),i+=8):(a=Ye(e,i),s=Ye(e,i+8),i+=16),i+=2;var o=e.length+s,l=Ke(e,i);i+=2;for(var u=0;u<l;u++){var c=i,d=je(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return ke.warn("SIDX has hierarchical references (not supported)"),null;var f=je(e,c);c+=4,t.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+h-1}}),o+=h,i=c+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function Xe(e){for(var t=[],r=qe(e,["moov","trak"]),i=0;i<r.length;i++){var n=r[i],a=qe(n,["tkhd"])[0];if(a){var s=a[0],o=je(a,0===s?12:20),l=qe(n,["mdia","mdhd"])[0];if(l){var u=je(l,0===(s=l[0])?12:20),c=qe(n,["mdia","hdlr"])[0];if(c){var d=Ve(c.subarray(8,12)),h={soun:De,vide:Ce}[d],f=Qe(qe(n,["mdia","minf","stbl","stsd"])[0]);h?(t[o]={timescale:u,type:h,stsd:f},t[h]=fe({timescale:u,id:o},f)):t[o]={timescale:u,type:d,stsd:f}}}}}return qe(e,["moov","mvex","trex"]).forEach(function(e){var r=je(e,4),i=t[r];i&&(i.default={duration:je(e,12),flags:je(e,20)})}),t}function Qe(e){var t,r=e.subarray(8),i=r.subarray(86),n=Ve(r.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=qe(r,[n])[0];qe(o.subarray("enca"===n?28:78),["sinf"]).forEach(function(e){var t=qe(e,["schm"])[0];if(t){var r=Ve(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=qe(e,["frma"])[0];i&&(a=Ve(i))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=qe(i,["avcC"])[0];u&&u.length>3&&(a+="."+Ze(u[1])+Ze(u[2])+Ze(u[3]),t=$e("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var c=qe(r,[n])[0],d=qe(c.subarray(28),["esds"])[0];if(d&&d.length>7){var h=4;if(3!==d[h++])break;h=Je(d,h),h+=2;var f=d[h++];if(128&f&&(h+=2),64&f&&(h+=d[h++]),4!==d[h++])break;h=Je(d,h);var v=d[h++];if(64!==v)break;if(a+="."+Ze(v),h+=12,5!==d[h++])break;h=Je(d,h);var g=d[h++],p=(248&g)>>3;31===p&&(p+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+p}break;case"hvc1":case"hev1":var m=qe(i,["hvcC"])[0];if(m&&m.length>12){var y=m[1],E=["","A","B","C"][y>>6],k=31&y,T=je(m,2),S=(32&y)>>5?"H":"L",b=m[12],A=m.subarray(6,12);a+="."+E+k,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(T).toString(16).toUpperCase(),a+="."+S+b;for(var L="",I=A.length;I--;){var R=A[I];if(R||L)L="."+R.toString(16).toUpperCase()+L}a+=L}t=$e("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=$e(a,i)||a;break;case"vp09":var w=qe(i,["vpcC"])[0];if(w&&w.length>6){var P=w[4],x=w[5],D=w[6]>>4&15;a+="."+et(P)+"."+et(x)+"."+et(D)}break;case"av01":var C=qe(i,["av1C"])[0];if(C&&C.length>2){var _=C[1]>>>5,M=31&C[1],O=C[2]>>>7?"H":"M",F=(64&C[2])>>6,N=(32&C[2])>>5,U=2===_&&F?N?12:10:F?10:8,B=(16&C[2])>>4,G=(8&C[2])>>3,H=(4&C[2])>>2,V=3&C[2];a+="."+_+"."+et(M)+O+"."+et(U)+"."+B+"."+G+H+V+"."+et(1)+"."+et(1)+"."+et(1)+".0",t=$e("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function $e(e,t){var r=qe(t,["dvvC"]),i=r.length?r[0]:qe(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+et(n)+"."+et(a)}}function Je(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function Ze(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function et(e){return(e<10?"0":"")+e}function tt(e,t){qe(e,["moov","trak"]).forEach(function(e){var r=qe(e,["mdia","minf","stbl","stsd"])[0];if(r){var i=r.subarray(8),n=qe(i,["enca"]),a=n.length>0;a||(n=qe(i,["encv"])),n.forEach(function(e){qe(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var r=rt(e);r&&t(r,a)})})}})}function rt(e){var t=qe(e,["schm"])[0];if(t){var r=Ve(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=qe(e,["schi","tenc"])[0];if(i)return i}}}function it(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function nt(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return qe(i,["moof"]).map(function(o){var l=o.byteOffset-8;qe(o,["traf"]).map(function(o){var u=qe(o,["tfdt"]).map(function(e){var t=e[0],r=je(e,4);return 1===t&&(r*=Math.pow(2,32),r+=je(e,8)),r/n})[0];return void 0!==u&&(e=u),qe(o,["tfhd"]).map(function(u){var c=je(u,4),d=16777215&je(u,0),h=0,f=!!(16&d),v=0,g=!!(32&d),p=8;c===a&&(!!(1&d)&&(p+=8),!!(2&d)&&(p+=4),!!(8&d)&&(h=je(u,p),p+=4),f&&(v=je(u,p),p+=4),g&&(p+=4),"video"===t.type&&(s=at(t.codec)),qe(o,["trun"]).map(function(a){var o=a[0],u=16777215&je(a,0),c=!!(1&u),d=0,f=!!(4&u),g=!!(256&u),p=0,m=!!(512&u),y=0,E=!!(1024&u),k=!!(2048&u),T=0,S=je(a,4),b=8;c&&(d=je(a,b),b+=4),f&&(b+=4);for(var A=d+l,L=0;L<S;L++){if(g?(p=je(a,b),b+=4):p=h,m?(y=je(a,b),b+=4):y=v,E&&(b+=4),k&&(T=0===o?je(a,b):We(a,b),b+=4),t.type===Ce)for(var I=0;I<y;){var R=je(i,A);if(st(s,i[A+=4]))ot(i.subarray(A,A+R),s?2:1,e+T/n,r);A+=R,I+=R+4}e+=p/n}}))})})}),r}function at(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function st(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6===(31&t)}function ot(e,t,r,i){var n=lt(e),a=0;a+=t;for(var s=0,o=0,l=0;a<n.length;){s=0;do{if(a>=n.length)break;s+=l=n[a++]}while(255===l);o=0;do{if(a>=n.length)break;o+=l=n[a++]}while(255===l);var u=n.length-a,c=a;if(o<u)a+=o;else if(o>u){ke.error("Malformed SEI payload. ".concat(o," is too small, only ").concat(u," bytes left to parse."));break}if(4===s){if(181===n[c++]){var d=Ke(n,c);if(c+=2,49===d){var h=je(n,c);if(c+=4,1195456820===h){var f=n[c++];if(3===f){var v=n[c++],g=64&v,p=g?2+3*(31&v):0,m=new Uint8Array(p);if(g){m[0]=v;for(var y=1;y<p;y++)m[y]=n[c++]}i.push({type:f,payloadType:s,pts:r,bytes:m})}}}}}else if(5===s&&o>16){for(var E=[],k=0;k<16;k++){var T=n[c++].toString(16);E.push(1==T.length?"0"+T:T),3!==k&&5!==k&&7!==k&&9!==k||E.push("-")}for(var S=o-16,b=new Uint8Array(S),A=0;A<S;A++)b[A]=n[c++];i.push({payloadType:s,pts:r,uuid:E.join(""),userData:be(b),userDataBytes:b})}}}function lt(e){for(var t=e.byteLength,r=[],i=1;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;var n=t-r.length,a=new Uint8Array(n),s=0;for(i=0;i<n;s++,i++)s===r[0]&&(s++,r.shift()),a[i]=e[s];return a}function ut(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var i,n;i=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=r.length,a=8,s=n;s--;)a+=r[s].byteLength;var o=new Uint8Array(a);for(o[0]=a>>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s<n;s++)o.set(r[s],a),a+=r[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,r)}function ct(e){var t=e.getUint32(0),r=e.byteOffset,i=e.byteLength;if(i<t)return{offset:r,size:i};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a=e.buffer,s=Ae(new Uint8Array(a,r+12,16)),o=null,l=0;if(0===n)l=28;else{var u=e.getUint32(28);if(!u||i<32+16*u)return{offset:r,size:t};o=[];for(var c=0;c<u;c++)o.push(new Uint8Array(a,r+32+16*c,16));l=32+16*u}if(!l)return{offset:r,size:t};var d=e.getUint32(l);return t-32<d?{offset:r,size:t}:{version:n,systemId:s,kids:o,data:new Uint8Array(a,r+l+4,d),offset:r,size:t}}var dt=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},ht={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 ft(e,t){var r=ht[t];return!!r&&!!r[e.slice(0,4)]}function vt(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!gt(e,t,r)})}function gt(e,t){var r,i=Te(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(r=null==i?void 0:i.isTypeSupported(pt(e,t)))&&r}function pt(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function mt(e){if(e){var t=e.substring(0,4);return ht.video[t]}return 2}function yt(e){var t=dt();return e.split(",").reduce(function(e,r){var i=t&&at(r)?9:ht.video[r];return i?(2*i+e)/(e?3:2):(ht.audio[r]+e)/(e?2:1)},0)}var Et={};var kt=/flac|opus|mp4a\.40\.34/i;function Tt(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(kt,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(Et[e])return Et[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var n;if(gt(r[i],"audio",t))return Et[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=Te(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)})}function St(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(bt(e,"audio")||bt(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function bt(e,t){return ft(e,t)&&gt(e,t)}function At(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function Lt(e){var t=Te(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function It(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Rt={supported:!1,smooth:!1,powerEfficient:!1},wt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Pt(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Rt],error:e}}function xt(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve(wt);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=Ct(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(function(e){var t={contentType:pt(At(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=Ct(e);if(n&&e.audioGroups)return e.audioGroups.reduce(function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach(function(t){var i={contentType:pt(t,"audio"),bitrate:r?Dt(t,a):a};s&&(i.channels=""+s),e.push(i)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length,c=o||1*u||1;c--;){var d={type:"media-source"};if(o&&(d.video=s[c%o]),u){d.audio=l[c%u];var h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}a.push(d)}if(n){var f=navigator.userAgent;if(n.split(",").some(function(e){return at(e)})&&dt())return Promise.resolve(Pt(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (".concat(f,")")),a))}return Promise.all(a.map(function(e){var t=function(e){var t="",r=e.audio,i=e.video;if(i){var n=It(i.contentType);t+="".concat(n,"_r").concat(i.height,"x").concat(i.width,"f").concat(Math.ceil(i.framerate)).concat(i.transferFunction||"sd","_").concat(Math.ceil(i.bitrate/1e5))}if(r){var a=It(r.contentType);t+="".concat(i?"_":"").concat(a,"_c").concat(r.channels)}return t}(e);return i[t]||(i[t]=r.decodingInfo(e))})).then(function(e){return{supported:!e.some(function(e){return!e.supported}),configurations:a,decodingInfoResults:e}}).catch(function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}})}function Dt(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function Ct(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var _t=["NONE","TYPE-0","TYPE-1",null];var Mt=["SDR","PQ","HLG"];var Ot="",Ft="YES",Nt="v2";function Ut(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?Nt:Ft:Ot}var Bt=function(){return o(function e(t,r,i){a(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=i},[{key:"addDirectives",value:function(e){var 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}}])}(),Gt=function(){return o(function e(t){if(a(this,e),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=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;var i=null==(r=t.supplemental)?void 0:r.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=",".concat(i.substring(0,4)))}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)},[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"hasAudioGroup",value:function(e){return Ht(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return Ht(this._subtitleGroups,e)}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"addGroupId",value:function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}},{key:"addFallback",value:function(){}}])}();function Ht(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Vt(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var n="SDR"!==(i=t.allowedVideoRanges||Mt.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}var Kt=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"===S(i)&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function jt(e,t){ke.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function Yt(e){return e.reduce(function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Wt(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function qt(e,t,r){if("attrs"in e){var i=t.indexOf(e);if(-1!==i)return i}for(var n=0;n<t.length;n++){if(zt(e,t[n],r))return n}return-1}function zt(e,t,r){var i=e.groupId,n=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===n||t.name===n)&&(void 0===a||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===a||t.assocLang===s)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=e.split(","),i=t.split(",");return r.length===i.length&&!r.some(function(e){return-1===i.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Xt(e,t){var r=e.audioCodec,i=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function Qt(e,t,r){for(var i=t;i>-1;i--)if(r(e[i]))return i;for(var n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function $t(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}var Jt=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["abr",e.logger])).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,n=i.fragCurrent,a=i.partCurrent,s=i.hls,o=s.autoLevelEnabled,l=s.media;if(n&&l){var u=performance.now(),c=a?a.stats:n.stats,d=a?a.duration:n.duration,h=u-c.loading.start,f=s.minAutoLevel,v=n.level,g=r._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var p=g>-1&&g!==v,m=!!e||p;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(m||null!==y){var E=r.bwEstimator.getEstimateTTFB(),k=Math.abs(l.playbackRate);if(!(h<=Math.max(E,d/(2*k)*1e3))){var T=y?y.len/k:0,S=c.loading.first?c.loading.first-c.loading.start:-1,b=c.loaded&&S>-1,A=r.getBwEstimate(),L=s.levels,I=L[v],R=Math.max(c.loaded,Math.round(d*(n.bitrate||I.averageBitrate)/8)),w=b?h-S:h;w<1&&b&&(w=Math.min(h,8*c.loaded/A));var P=b?1e3*c.loaded/w:0,x=E/1e3,D=P?(R-c.loaded)/P:8*R/A+x;if(!(D<=T)){var C,_=P?8*P:A,M=!0===(null==(t=(null==e?void 0:e.details)||r.hls.latestLevelDetails)?void 0:t.live),O=r.hls.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(C=v-1;C>f;C--){var N=L[C].maxBitrate,U=!L[C].details||M;if((F=r.getTimeToLoadFrag(x,_,d*N,U))<Math.min(T,d+x))break}if(!(F>=D||F>10*d)){b?r.bwEstimator.sample(h-Math.min(E,S),c.loaded):r.bwEstimator.sampleTTFB(h);var B=L[C].maxBitrate;r.getBwEstimate()*O>B&&r.resetEstimator(B);var G=r.findBestLevel(B,f,C,0,T,1,1);G>-1&&(C=G),r.warn("Fragment ".concat(n.sn).concat(a?" part "+a.index:""," of level ").concat(v," is loading too slowly;\n Fragment duration: ").concat(n.duration.toFixed(3),"\n Time to underbuffer: ").concat(T.toFixed(3)," s\n Estimated load time for current fragment: ").concat(D.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(F.toFixed(3)," s\n TTFB estimate: ").concat(0|S," ms\n Current BW estimate: ").concat(X(A)?0|A:"Unknown"," bps\n New BW estimate: ").concat(0|r.getBwEstimate()," bps\n Switching to level ").concat(C," @ ").concat(0|B," bps")),s.nextLoadLevel=s.nextAutoLevel=C,r.clearTimer();var H=function(){if(r.clearTimer(),r.fragCurrent===n&&r.hls.loadLevel===C&&C>0){var e=r.getStarvationDelay();if(r.warn("Aborting inflight request ".concat(C>0?"and switching down":"","\n Fragment duration: ").concat(n.duration.toFixed(3)," s\n Time to underbuffer: ").concat(e.toFixed(3)," s")),n.abortRequests(),r.fragCurrent=r.partCurrent=null,C>f){var t=r.findBestLevel(r.hls.levels[f].bitrate,f,C,0,e,1,1);-1===t&&(t=f),r.hls.nextLoadLevel=r.hls.nextAutoLevel=t,r.resetEstimator(r.hls.levels[t].bitrate)}}};p||D>2*F?H():r.timer=self.setInterval(H,1e3*F),s.trigger(ee.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:c})}}}}}}}},r.hls=e,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}return d(t,e),o(t,[{key:"resetEstimator",value:function(e){e&&(this.log("setting initial bwe to ".concat(e)),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}},{key:"initEstimator",value:function(){var e=this.hls.config;return new ue(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.FRAG_LOADING,this.onFragLoading,this),e.on(ee.FRAG_LOADED,this.onFragLoaded,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(ee.ERROR,this.onError,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}},{key:"onManifestLoading",value:function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}},{key:"onLevelsUpdated",value:function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}},{key:"onMaxAutoLevelUpdated",value:function(){this.firstSelection=-1,this.nextAutoLevelKey=""}},{key:"onFragLoading",value:function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}},{key:"onLevelSwitching",value:function(e,t){this.clearTimer()}},{key:"onError",value:function(e,t){if(!t.fatal)switch(t.details){case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Z.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}}},{key:"getTimeToLoadFrag",value:function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;X(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var r=t.frag,i=t.part,n=i?i.stats:r.stats;if(r.type===ae&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var a=i?i.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+n.loaded,l=(s.loaded?s.loaded.duration:0)+a;s.loaded={bytes:o,duration:l},s.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var u={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(ee.FRAG_BUFFERED,u),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}}},{key:"ignoreFragment",value:function(e){return e.type!==ae||"initSegment"===e.sn}},{key:"clearTimer",value:function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}},{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(i,r,t,0,n,1,1);if(a>-1)return a;var s=this.hls.firstLevel,o=Math.min(Math.max(s,r),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(s," clamped to ").concat(o)),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}},{key:"getAutoLevelKey",value:function(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}},{key:"getNextABRAutoLevel",value:function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,i,l,0,u,c);if(d>=0)return this.rebufferNotice=-1,d}var h=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;if(f)h=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-f,this.info("bitrate test took ".concat(Math.round(1e3*f),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*h)," ms")),u=c=1}var v=this.findBestLevel(o,a,i,l,h,u,c);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info("".concat(l?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(v))),v>-1)return v;var g=r.levels[a],p=r.loadLevelObj;return p&&(null==g?void 0:g.bitrate)<p.bitrate?a:r.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}},{key:"getBwEstimate",value:function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}},{key:"findBestLevel",value:function(e,t,r,i,n,a,s){var o,l=this,u=i+n,c=this.lastLoadedFragLevel,d=-1===c?this.hls.firstLevel:c,h=this.fragCurrent,f=this.partCurrent,v=this.hls,g=v.levels,p=v.allAudioTracks,m=v.loadLevel,y=v.config;if(1===g.length)return 0;var E,k=g[d],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),S=-1===m||-1===c,b="SDR",A=(null==k?void 0:k.frameRate)||0,L=y.audioPreference,I=y.videoPreference,R=this.audioTracksByGroup||(this.audioTracksByGroup=Yt(p)),w=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;var P=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce(function(e,r,i){if(!r.codecSet)return e;var n=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.minIndex=Math.min(a.minIndex,i),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,n&&n.forEach(function(e){if(e){var r=t.groups[e];r&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]}))}}),e},{})}(g,R,t,r)),x=function(e,t,r,i,n){for(var a=Object.keys(e),s=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==n?void 0:n.videoCodec,u=s&&2===parseInt(s),c=!1,d=!1,h=1/0,f=1/0,v=1/0,g=1/0,p=0,m=[],y=Vt(t,n),E=y.preferHDR,k=y.allowedVideoRanges,T=function(){var t=e[a[S]];c||(c=t.channels[2]>0),h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),v=Math.min(v,t.minBitrate),k.filter(function(e){return t.videoRanges[e]>0}).length>0&&(d=!0)},S=a.length;S--;)T();h=X(h)?h:0,f=X(f)?f:0;var b=Math.max(1080,h),A=Math.max(30,f);v=X(v)?v:r,r=Math.max(v,r),d||(t=void 0);var L=a.length>1;return{codecSet:a.reduce(function(t,i){var n=e[i];if(i===t)return t;if(m=d?k.filter(function(e){return n.videoRanges[e]>0}):[],L){if(n.minBitrate>r)return jt(i,"min bitrate of ".concat(n.minBitrate," > current estimate of ").concat(r)),t;if(!n.hasDefaultAudio)return jt(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return jt(i,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!n.channels[s])return jt(i,"no renditions with ".concat(s," channel sound found (channels options: ").concat(Object.keys(n.channels),")")),t}else if((!o||u)&&c&&0===n.channels[2])return jt(i,"no renditions with stereo sound found"),t;if(n.minHeight>b)return jt(i,"min resolution of ".concat(n.minHeight," > maximum of ").concat(b)),t;if(n.minFramerate>A)return jt(i,"min framerate of ".concat(n.minFramerate," > maximum of ").concat(A)),t;if(!m.some(function(e){return n.videoRanges[e]>0}))return jt(i,"no variants with VIDEO-RANGE of ".concat(Kt(m)," found")),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return jt(i,'video codec preference "'.concat(l,'" not found')),t;if(n.maxScore<p)return jt(i,"max score of ".concat(n.maxScore," < selected max of ").concat(p)),t}return t&&(yt(i)>=yt(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,p=n.maxScore,i)},void 0),videoRanges:m,preferHDR:E,minFramerate:f,minBitrate:v,minIndex:g}}(P,b,e,L,I),D=x.codecSet,C=x.videoRanges,_=x.minFramerate,M=x.minBitrate,O=x.minIndex,F=x.preferHDR;w=O,E=D,b=F?C[C.length-1]:C[0],A=_,e=Math.max(e,M),this.log("picked start tier ".concat(Kt(x)))}else E=null==k?void 0:k.codecSet,b=null==k?void 0:k.videoRange;for(var N,U,B=f?f.duration:h?h.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,H=[],V=function(){var t=g[K],o=K>d;if(!t)return 0;if(y.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var h=navigator.mediaCapabilities;"function"==typeof(null==h?void 0:h.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,c=u?parseInt(u):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group ".concat(r," not found"));Object.keys(i.channels).forEach(function(t){e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some(function(e){return at(e)})||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!d&&X(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,R,b,A,e,L)?(t.supportedPromise=xt(t,R,h,l.supportedCache),t.supportedPromise.then(function(e){if(l.hls){t.supportedResult=e;var r=l.hls.levels,i=r.indexOf(t);e.error?l.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(i," ").concat(Kt(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&l.log("MediaCapabilities decodingInfo for level ".concat(i," not smooth or powerEfficient: ").concat(Kt(e))):(l.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(i," ").concat(Kt(e))),i>-1&&r.length>1&&(l.log("Removing unsupported level ".concat(i)),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}}).catch(function(e){l.warn("Error handling MediaCapabilities decodingInfo: ".concat(e))})):t.supportedResult=wt}if((E&&t.codecSet!==E||b&&t.videoRange!==b||o&&A>t.frameRate||!o&&A>0&&A<t.frameRate||null!=(N=t.supportedResult)&&null!=(N=N.decodingInfoResults)&&N.some(function(e){return!1===e.smooth}))&&(!S||K!==w))return H.push(K),0;var v,p=t.details,k=(f?null==p?void 0:p.partTarget:null==p?void 0:p.averagetargetduration)||B;v=o?s*e:a*e;var I=B&&i>=2*B&&0===n?t.averageBitrate:t.maxBitrate,P=l.getTimeToLoadFrag(G,v,I*k,void 0===p);if(v>=I&&(K===c||0===t.loadError&&0===t.fragmentError)&&(P<=G||!X(P)||T&&!l.bitrateTestDelay||P<u)){var x=l.forcedAutoLevel;return K===m||-1!==x&&x===m||(H.length&&l.trace("Skipped level(s) ".concat(H.join(",")," of ").concat(r,' max with CODECS and VIDEO-RANGE:"').concat(g[H[0]].codecs,'" ').concat(g[H[0]].videoRange,'; not compatible with "').concat(E,'" ').concat(b)),l.info("switch candidate:".concat(d,"->").concat(K," adjustedbw(").concat(Math.round(v),")-bitrate=").concat(Math.round(v-I)," ttfb:").concat(G.toFixed(1)," avgDuration:").concat(k.toFixed(1)," maxFetchDuration:").concat(u.toFixed(1)," fetchDuration:").concat(P.toFixed(1)," firstSelection:").concat(S," codecSet:").concat(t.codecSet," videoRange:").concat(t.videoRange," hls.loadLevel:").concat(m))),S&&(l.firstSelection=K),{v:K}}},K=r;K>=t;K--)if(0!==(U=V())&&U)return U.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)}}])}(ve),Zt=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function er(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.005,a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===tr(r,i,a)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=Zt(t,tr.bind(null,r,i));return!o||o===e&&a?a:o}function tr(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2?arguments[2]:void 0;if(r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function rr(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function ir(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),Zt(n,function(e){return e.cc<t?1:e.cc>t?-1:(i=e,e.end<=r?1:e.start>r?-1:0)}),i||null}return null}function nr(e){switch(e.details){case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_TIMEOUT:case Z.LEVEL_LOAD_TIMEOUT:case Z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ar(e){return e.details.startsWith("key")}function sr(e){return ar(e)&&!!e.frag&&!e.frag.decryptdata}function or(e,t){var r=nr(t);return e.default["".concat(r?"timeout":"error","Retry")]}function lr(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function ur(e){return fe(fe({},e),{errorRetry:null,timeoutRetry:null})}function cr(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t<e.maxNumRetry&&(function(e){return dr(e)||!!e&&(e<400||e>499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function dr(e){return 0===e&&!1===navigator.onLine}var hr=0,fr=2,vr=3,gr=5,pr=0,mr=1,yr=2,Er=4,kr=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["error-controller",e.logger])).hls=void 0,r.playlistError=0,r.hls=e,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.ERROR,this.onError,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.ERROR,this.onError,this),e.off(ee.ERROR,this.onErrorOut,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.hls=null}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.playlistError=0}},{key:"getVariantLevelIndex",value:function(e){return(null==e?void 0:e.type)===ae?e.level:this.getVariantIndex()}},{key:"getVariantIndex",value:function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}},{key:"variantHasKey",value:function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(function(e){return i.indexOf(e.groupId)>=0}).some(function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)})}return!1}},{key:"onManifestLoading",value:function(){this.playlistError=0}},{key:"onLevelUpdated",value:function(){this.playlistError=0}},{key:"onError",value:function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Z.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=Tr());case Z.FRAG_GAP:case Z.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=fr);case Z.LEVEL_EMPTY_ERROR:case Z.LEVEL_PARSING_ERROR:var a,s=t.parent===ae?t.level:i.loadLevel;return void(t.details===Z.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(a=a.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,s)));case Z.LEVEL_LOAD_ERROR:case Z.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.SUBTITLE_LOAD_ERROR:case Z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===ie&&o.hasAudioGroup(n.groupId)||n.type===ne&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=fr,void(t.errorAction.flags=mr)}return;case Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:fr,flags:yr});case Z.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Z.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:fr,flags:Er});case Z.BUFFER_ADD_CODEC_ERROR:case Z.REMUX_ALLOC_ERROR:case Z.BUFFER_APPEND_ERROR:var l;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(l=t.level)?l:i.loadLevel);return;case Z.INTERNAL_EXCEPTION:case Z.BUFFER_APPENDING_ERROR:case Z.BUFFER_FULL_ERROR:case Z.LEVEL_SWITCH_ERROR:case Z.BUFFER_STALLED_ERROR:case Z.BUFFER_SEEK_OVER_HOLE:case Z.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Tr())}t.type===J.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Tr())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var r=or(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(cr(r,i,nr(e),e.response))return{action:gr,flags:pr,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=or(ar(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(i&&(e.details!==Z.FRAG_GAP&&i.fragmentError++,!sr(e)&&cr(o,l,nr(e),e.response)))return{action:gr,flags:pr,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,s===Z.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,c=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var h,f,v,g=null==(n=e.frag)?void 0:n.type,p=(g===se&&s===Z.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR))&&l.some(function(e){var t=e.audioCodec;return i.audioCodec!==t}),m="video"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR)&&l.some(function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r}),y=null!=(a=e.context)?a:{},E=y.type,k=y.groupId,T=function(){var t=(S+u)%l.length;if(t!==u&&t>=c&&t<=d&&0===l[t].loadError){var r=l[t];if(s===Z.FRAG_GAP&&g===ae&&e.frag){var n=l[t].details;if(n){var a=er(e.frag,n.fragments,e.frag.start);if(null!=a&&a.gap)return 0}}else{if(E===ie&&r.hasAudioGroup(k)||E===ne&&r.hasSubtitleGroup(k))return 0;if(g===se&&null!=(h=i.audioGroups)&&h.some(function(e){return r.hasAudioGroup(e)})||g===oe&&null!=(f=i.subtitleGroups)&&f.some(function(e){return r.hasSubtitleGroup(e)})||p&&i.audioCodec===r.audioCodec||m&&i.codecSet===r.codecSet||!p&&i.codecSet!==r.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(v=T())||1!==v););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:fr,flags:pr,nextAutoLevel:o}}return{action:fr,flags:mr}}},{key:"onErrorOut",value:function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case hr:break;case fr:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Z.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'.concat(t.sourceBufferName,'" sourceBuffer append error. Attempting to recover from media error.')),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}},{key:"sendAlternateToPenaltyBox",value:function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,n=r.nextAutoLevel;switch(i){case pr:this.switchLevel(e,n);break;case yr:var a=this.getVariantLevelIndex(e.frag),s=t.levels[a],o=null==s?void 0:s.attrs["HDCP-LEVEL"];if(r.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=_t[_t.indexOf(o)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'));break}case Er:var l=e.decryptdata;if(l){for(var u=this.hls.levels,c=u.length,d=c;d--;){var h,f;if(this.variantHasKey(u[d],l))this.log("Banned key found in level ".concat(d," (").concat(u[d].bitrate,'bps) or audio group "').concat(null==(h=u[d].audioGroups)?void 0:h.join(","),'" (').concat(null==(f=e.frag)?void 0:f.type," fragment) ").concat(Ae(l.keyId||[]))),u[d].fragmentError++,u[d].loadError++,this.log("Removing level ".concat(d," with key error (").concat(e.error,")")),this.hls.removeLevel(d)}var v=e.frag;if(this.hls.levels.length<c)r.resolved=!0;else if(v&&v.type!==ae){var g=v.decryptdata;g&&!l.matches(g)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(e,n)}}},{key:"switchLevel",value:function(e,t){if(void 0!==t&&e.errorAction&&(this.warn("switching to level ".concat(t," after ").concat(e.details)),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===Z.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=It(e.mimeType),i=this.hls.levels,n=i.length;n--;)i[n]["".concat(e.sourceBufferName,"Codec")]===r&&(this.log("Removing level ".concat(n," for ").concat(e.details,' ("').concat(r,'" not supported)')),this.hls.removeLevel(n))}}])}(ve);function Tr(e){var t={action:hr,flags:pr};return e&&(t.resolved=!0),t}var Sr="NOT_LOADED",br="APPENDING",Ar="PARTIAL",Lr="OK",Ir=function(){return o(function e(t){a(this,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=t,this._registerListeners()},[{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.FRAG_LOADED,this.onFragLoaded,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this))}},{key:"destroy",value:function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}},{key:"getAppendedFrag",value:function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}},{key:"getBufferedFrag",value:function(e,t){return this.getFragAtPos(e,t,!0)}},{key:"getFragAtPos",value:function(e,t,r){for(var i=this.fragments,n=Object.keys(i),a=n.length;a--;){var s=i[n[a]];if((null==s?void 0:s.body.type)===t&&(!r||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,r,i,n){var a=this;this.timeRanges&&(this.timeRanges[e]=t);var s=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(i){var o=a.fragments[i];if(o&&!(s>=o.body.sn))if(o.buffered||o.loaded&&!n){var l=o.range[e];l&&(0!==l.time.length?l.time.some(function(e){var r=!a.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&a.removeFragment(o.body),r}):a.removeFragment(o.body))}else o.body.type===r&&a.removeFragment(o.body)})}},{key:"detectPartialFragments",value:function(e){var t=this,r=this.timeRanges;if(r&&"initSegment"!==e.frag.sn){var i=e.frag,n=wr(i),a=this.fragments[n];if(!(!a||a.buffered&&i.gap)){var s=!i.relurl;if(Object.keys(r).forEach(function(n){var o=i.elementaryStreams[n];if(o){var l=r[n],u=s||!0===o.partial;a.range[n]=t.getBufferedTimes(i,e.part,u,l)}}),a.loaded=null,Object.keys(a.range).length)a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Rr(a)||this.removeParts(i.sn-1,i.type);else this.removeFragment(a.body)}}}},{key:"removeParts",value:function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Pr(r,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var r=wr(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}},{key:"getBufferedTimes",value:function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<i.length;u++){var c=i.start(u)-this.bufferPadding,d=i.end(u)+this.bufferPadding;if(l>=c&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(a<d&&s>c){var h=Math.max(a,i.start(u)),f=Math.min(s,i.end(u));f>h&&(n.partial=!0,n.time.push({startPTS:h,endPTS:f}))}else if(s<=c)break}return n}},{key:"getPartialFragment",value:function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&Rr(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))}),n}},{key:"isEndListAppended",value:function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Rr(t))}},{key:"getState",value:function(e){var t=wr(e),r=this.fragments[t];return r?r.buffered?Rr(r)?Ar:Lr:br:Sr}},{key:"isTimeBuffered",value:function(e,t,r){for(var i,n,a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1}},{key:"onManifestLoading",value:function(){this.removeAllFragments()}},{key:"onFragLoaded",value:function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=wr(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var r=t.frag,i=t.part,n=t.timeRanges,a=t.type;if("initSegment"!==r.sn){var s=r.type;if(i){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(i)}this.timeRanges=n;var l=n[a];this.detectEvictedFragments(a,l,s,i)}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=wr(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1}},{key:"hasParts",value:function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}},{key:"removeFragmentsInRange",value:function(e,t,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=wr(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Pr(r,function(e){return e.fragment.sn!==i})}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}},{key:"removeAllFragments",value:function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(function(e){return e.clearElementaryStreamInfo()})}}])}();function Rr(e){var t,r,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial)}function wr(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function Pr(e,t){return e.filter(function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r})}var xr=0,Dr=1,Cr=function(){return o(function e(t,r,i){a(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=i},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case xr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Dr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode ".concat(this.aesMode))}}}])}();var _r=function(){return o(function e(){a(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()},[{key:"uint8ArrayToUint32Array_",value:function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256),f=0,v=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var p=v^v<<1^v<<2^v<<3^v<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var m=h[f],y=h[m],E=h[y],k=257*h[p]^16843008*p;i[f]=k<<24|k>>>8,n[f]=k<<16|k>>>16,a[f]=k<<8|k>>>24,s[f]=k,k=16843009*E^65537*y^257*m^16843008*f,l[p]=k<<24|k>>>8,u[p]=k<<16|k>>>16,c[p]=k<<8|k>>>24,d[p]=k,f?(f=m^h[h[h[E^m]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var a,s,o,l,u=this.ksRows=4*(n+6+1),c=this.keySchedule=new Uint32Array(u),d=this.invKeySchedule=new Uint32Array(u),h=this.sBox,f=this.rcon,v=this.invSubMix,g=v[0],p=v[1],m=v[2],y=v[3];for(a=0;a<u;a++)a<n?o=c[a]=t[a]:(l=o,a%n===0?(l=h[(l=l<<8|l>>>24)>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l],l^=f[a/n|0]<<24):n>6&&a%n===4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),c[a]=o=(c[a-n]^l)>>>0);for(s=0;s<u;s++)a=u-s,l=3&s?c[a]:c[a-4],d[s]=s<4||a<=4?l:g[h[l>>>24]]^p[h[l>>>16&255]]^m[h[l>>>8&255]]^y[h[255&l]],d[s]=d[s]>>>0}}},{key:"networkToHostOrderSwap",value:function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var i,n,a,s,o,l,u,c,d,h,f,v,g,p,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,k=this.invSubMix,T=k[0],S=k[1],b=k[2],A=k[3],L=this.uint8ArrayToUint32Array_(r),I=L[0],R=L[1],w=L[2],P=L[3],x=new Int32Array(e),D=new Int32Array(x.length),C=this.networkToHostOrderSwap;t<x.length;){for(d=C(x[t]),h=C(x[t+1]),f=C(x[t+2]),v=C(x[t+3]),o=d^y[0],l=v^y[1],u=f^y[2],c=h^y[3],g=4,p=1;p<m;p++)i=T[o>>>24]^S[l>>16&255]^b[u>>8&255]^A[255&c]^y[g],n=T[l>>>24]^S[u>>16&255]^b[c>>8&255]^A[255&o]^y[g+1],a=T[u>>>24]^S[c>>16&255]^b[o>>8&255]^A[255&l]^y[g+2],s=T[c>>>24]^S[o>>16&255]^b[l>>8&255]^A[255&u]^y[g+3],o=i,l=n,u=a,c=s,g+=4;i=E[o>>>24]<<24^E[l>>16&255]<<16^E[u>>8&255]<<8^E[255&c]^y[g],n=E[l>>>24]<<24^E[u>>16&255]<<16^E[c>>8&255]<<8^E[255&o]^y[g+1],a=E[u>>>24]<<24^E[c>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[g+2],s=E[c>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&u]^y[g+3],D[t]=C(i^I),D[t+1]=C(s^R),D[t+2]=C(a^w),D[t+3]=C(n^P),I=d,R=h,w=f,P=v,t+=4}return D.buffer}}])}(),Mr=function(){return o(function e(t,r,i){a(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=r,this.aesMode=i},[{key:"expandKey",value:function(){var e=function(e){switch(e){case xr:return"AES-CBC";case Dr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode ".concat(e))}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}])}();var Or=function(){return o(function e(t){var r=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).removePKCS7Padding,i=void 0===r||r;if(a(this,e),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=t.enableSoftwareAES,this.removePKCS7Padding=i,i)try{var n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle},[{key:"destroy",value:function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{key:"isSync",value:function(){return this.useSoftware}},{key:"flush",value:function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r,i,n,a=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(i=(r=a).byteLength,(n=i&&new DataView(r.buffer).getUint8(i-1))?r.slice(0,i-n):r):a}},{key:"reset",value:function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}},{key:"decrypt",value:function(e,t,r,i){var n=this;return this.useSoftware?new Promise(function(a,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);n.softwareDecrypt(o,t,r,i);var l=n.flush();l?a(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)}},{key:"softwareDecrypt",value:function(e,t,r,i){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(i!==xr||16!==t.byteLength)return ke.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=it(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new _r),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,r,i){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new Mr(this.subtle,t,i)}return this.fastAesKey.expandKey().then(function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new Cr(n.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return ke.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),n.onWebCryptoError(e,t,r,i)})}},{key:"onWebCryptoError",value:function(e,t,r,i){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}},{key:"getValidChunk",value:function(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(ke.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),Fr=Math.pow(2,17),Nr=function(){return o(function e(t){a(this,e),this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t},[{key:"destroy",value:function(){this.loader&&(this.loader.destroy(),this.loader=null)}},{key:"abort",value:function(){this.loader&&this.loader.abort()}},{key:"load",value:function(e,t){var r=this,i=e.url;if(!i)return Promise.reject(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(i?"part list":"url")),networkDetails:null}));this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(r.loader&&r.loader.destroy(),e.gap){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void l(Br(e));e.gap=!1}var u=r.loader=a?new a(n):new s(n),c=Ur(e);e.loader=u;var d=ur(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Fr};e.stats=u.stats;var f={onSuccess:function(t,i,n,a){r.resetLoader(e,u);var s=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),o({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,n,a,s){r.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:fe({url:i,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:a,stats:s}))},onAbort:function(t,i,n){r.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,i,n){r.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:n,stats:t}))}};t&&(f.onProgress=function(r,i,n,a){return t({frag:e,part:null,payload:n,networkDetails:a})}),u.load(c,h,f)})}},{key:"loadPart",value:function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(i.loader&&i.loader.destroy(),e.gap||t.gap)l(Br(e,t));else{var u=i.loader=a?new a(n):new s(n),c=Ur(e,t);e.loader=u;var d=ur(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Fr};t.stats=u.stats,u.load(c,h,{onSuccess:function(n,a,s,l){i.resetLoader(e,u),i.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:n.data,networkDetails:l};r(c),o(c)},onError:function(r,n,a,s){i.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:fe({url:c.url,data:void 0},r),error:new Error("HTTP Error ".concat(r.code," ").concat(r.text)),networkDetails:a,stats:s}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,n,a){i.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:a,stats:r}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end}},{key:"resetLoader",value:function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}])}();function Ur(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=r||e,n={frag:e,part:r,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},a=i.byteRangeStartOffset,s=i.byteRangeEndOffset;if(X(a)&&X(s)){var o,l=a,u=s;if("initSegment"===e.sn&&("AES-128"===(t=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===t)){var c=s-a;c%16&&(u=s+(16-c%16)),0!==a&&(n.resetIV=!0,l=a-16)}n.rangeStart=l,n.rangeEnd=u}return n}function Br(e,t){var r=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),i={type:J.MEDIA_ERROR,details:Z.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Gr(i)}var Gr=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e.error.message])).data=void 0,r.data=e,r}return d(t,e),o(t)}(L(Error)),Hr=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[e,r]))._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}return d(t,e),o(t,[{key:"destroy",value:function(){this.onHandlerDestroying(),this.onHandlerDestroyed()}},{key:"onHandlerDestroying",value:function(){this.clearNextTick(),this.clearInterval()}},{key:"onHandlerDestroyed",value:function(){}},{key:"hasInterval",value:function(){return!!this._tickInterval}},{key:"hasNextTick",value:function(){return!!this._tickTimer}},{key:"setInterval",value:function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}},{key:"clearInterval",value:function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}},{key:"clearNextTick",value:function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}},{key:"tick",value:function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}},{key:"tickImmediate",value:function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{key:"doTick",value:function(){}}])}(ve),Vr=o(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];a(this,e),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=t,this.sn=r,this.id=i,this.size=n,this.part=s,this.partial=o});var Kr={length:0,start:function(){return 0},end:function(){return 0}},jr=function(){function e(){a(this,e)}return o(e,null,[{key:"isBuffered",value:function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}},{key:"bufferInfo",value:function(t,r,i){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var i=-1,n=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<r?e[a].end>o&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,c=t,d=t,h=0;h<n.length;h++){var f=n[h].start,v=n[h].end;if(-1===i&&t>=f&&t<=v&&(i=h),t+r>=f&&t<v)c=f,u=(d=v)-t;else if(t+r<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:i}}},{key:"getBuffered",value:function(e){try{return e.buffered||Kr}catch(e){return ke.log("failed to get media.buffered",e),Kr}}}])}(),Yr=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wr(e){return Yr.test(e)}function qr(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(Yr,function(t){var i=t.substring(2,t.length-1),n=null==r?void 0:r[i];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(i,'"'))),t):n})}return t}function zr(e,t,r){var i,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'.concat(i,'" does not match any query parameter in URI: "').concat(r,'"'));n=s.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(t.message)))}}else i=t.NAME,n=t.VALUE;i in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(i,'"'))):a[i]=n||""}function Xr(e,t,r){var i=t.IMPORT;if(r&&i in r){var n=e.variableList;n||(e.variableList=n={}),n[i]=r[i]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(i,'"')))}var Qr=/^(\d+)x(\d+)$/,$r=/(.+?)=(".*?"|.*?)(?:,|$)/g,Jr=function(){return o(function e(t,r){a(this,e),"string"==typeof t&&(t=e.parseAttrList(t,r)),de(this,t)},[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(e){return"X-"===e.substring(0,2)})}},{key:"decimalInteger",value:function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null}},{key:"hexadecimalIntegerAsNumber",value:function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"optionalFloat",value:function(e,t){var r=this[e];return r?parseFloat(r):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce(function(e,t){return e[t.toLowerCase()]=!0,e},t)}},{key:"bool",value:function(e){return"YES"===this[e]}},{key:"decimalResolution",value:function(e){var t=Qr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var r,i={};for($r.lastIndex=0;null!==(r=$r.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=qr(t,a);else if(!o&&!s)switch(n){case"CLOSED-CAPTIONS":if("NONE"===a)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":ke.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}i[n]=a}return i}}])}();function Zr(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function ei(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var ti=function(){return o(function e(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(a(this,e),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==r?void 0:r.tagAnchor)||null,this.tagOrder=null!=(i=null==r?void 0:r.tagOrder)?i:n,r){var s=r.attr;for(var o in s)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==s[o]){ke.warn('DATERANGE tag attribute: "'.concat(o,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=o;break}t=de(new Jr({}),s,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var l=(null==r?void 0:r.endDate)||new Date(this.attr["END-DATE"]);X(l.getTime())&&(this._endDate=l)}},[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var 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}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(ke.warn('Expected tagAnchor Fragment with PDT set for DateRange "'.concat(this.id,'": ').concat(e)),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(X(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&X(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)}}])}(),ri=function(){return o(function e(t){a(this,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=t},[{key:"reloaded",value:function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}},{key:"hasKey",value:function(e){return this.encryptedFragments.some(function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}},{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&X(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function ii(e,t){return e.length===t.length&&!e.some(function(e,r){return e!==t[r]})}function ni(e,t){return!e&&!t||!(!e||!t)&&ii(e,t)}function ai(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function si(e){switch(e){case"AES-128":case"AES-256":return xr;case"AES-256-CTR":return Dr;default:throw new Error("invalid full segment method ".concat(e))}}function oi(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function li(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function ui(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ci(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=oi(l)):(t=li(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var di="undefined"!=typeof self?self:void 0,hi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fi="org.w3.clearkey",vi="com.apple.streamingkeydelivery",gi="com.microsoft.playready",pi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function mi(e){switch(e){case vi:return hi.FAIRPLAY;case gi:return hi.PLAYREADY;case pi:return hi.WIDEVINE;case fi:return hi.CLEARKEY}}function yi(e){switch(e){case hi.FAIRPLAY:return vi;case hi.PLAYREADY:return gi;case hi.WIDEVINE:return pi;case hi.CLEARKEY:return fi}}function Ei(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[hi.FAIRPLAY,hi.WIDEVINE,hi.PLAYREADY,hi.CLEARKEY].filter(function(e){return!!t[e]}):[];return!i[hi.WIDEVINE]&&r&&i.push(hi.WIDEVINE),i}var ki,Ti=null!=di&&null!=(ki=di.navigator)&&ki.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Si(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),i=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){var a=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(a){var s=oi(a).subarray(0,16);return ui(s),s}}return null}var bi={},Ai=function(){function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5?arguments[5]:void 0;a(this,e),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=t,this.uri=r,this.keyFormat=i,this.keyFormatVersions=n,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ai(t),null!=o&&o.startsWith("0x")&&(this.keyId=new Uint8Array(Le(o)))}return o(e,[{key:"matches",value:function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ii(e.keyFormatVersions,this.keyFormatVersions)&&ni(e.iv,this.iv)&&ni(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(ai(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case vi:case pi:case gi:case fi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,r){if(!this.encrypted||!this.uri)return null;if(ai(this.method)){var i=this.iv;return i||("number"!=typeof t&&(ke.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),i=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){var n=bi[this.uri];if(n&&!ii(this.keyId,n)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var a,s=ci(this.uri);if(s)switch(this.keyFormat){case pi:if(this.pssh=s,!this.keyId){var o=function(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,i=0;i+32<r;){var n=ct(new DataView(e,i));t.push(n),i+=n.size}return t}(s.buffer);if(o.length){var l,u=o[0];this.keyId=null!=(l=u.kids)&&l.length?u.kids[0]:null}}this.keyId||(this.keyId=Li(r));break;case gi:var c=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ut(c,0,s),this.keyId=Si(s);break;default:var d=s.subarray(0,16);if(16!==d.length){var h=new Uint8Array(16);h.set(d,16-d.length),d=h}this.keyId=d}this.keyId&&16===this.keyId.byteLength||(a=function(e){var t=null==e?void 0:e[pi];if(t)return t.keyId;return null}(r),a||(a=Li(r))||(a=bi[this.uri]),a&&(this.keyId=a,e.setKeyIdForUri(this.uri,a)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){bi={}}},{key:"setKeyIdForUri",value:function(e,t){bi[e]=t}}])}();function Li(e){var t=null==e?void 0:e[gi];if(t){var r=ci(t.uri);if(r)return Si(r)}return null}var Ii=/#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,Ri=/#EXT-X-MEDIA:(.*)/g,wi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),xi=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("|")),Di=function(){function e(){a(this,e)}return o(e,null,[{key:"findGroup",value:function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}}},{key:"resolve",value:function(e,t){return Pe.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return wi.test(e)}},{key:"parseMasterPlaylist",value:function(t,r){var i,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Wr(t)},a=[];if(Ii.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(i=Ii.exec(t));)if(i[1]){var s,o=new Jr(i[1],n),l=qr(n,i[2]),u={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,r)},c=o.decimalResolution("RESOLUTION");c&&(u.width=c.width,u.height=c.height),Fi(o.CODECS,u);var d=o["SUPPLEMENTAL-CODECS"];d&&(u.supplemental={},Fi(d,u.supplemental)),null!=(s=u.unknownCodecs)&&s.length||a.push(u),n.levels.push(u)}else if(i[3]){var h=i[3],f=i[4];switch(h){case"SESSION-DATA":var v=new Jr(f,n),g=v["DATA-ID"];g&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[g]=v);break;case"SESSION-KEY":var p=Mi(f,r,n);p.encrypted&&p.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(p)):ke.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(f,'"'));break;case"DEFINE":zr(n,new Jr(f,n),r);break;case"CONTENT-STEERING":var m=new Jr(f,n);n.contentSteering={uri:e.resolve(m["SERVER-URI"],r),pathwayId:m["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Oi(f)}}var y=a.length>0&&a.length<n.levels.length;return n.levels=y?a:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n}},{key:"parseMasterPlaylistMedia",value:function(t,r,i){var n,a={},s=i.levels,o={AUDIO:s.map(function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}}),SUBTITLES:s.map(function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}}),"CLOSED-CAPTIONS":[]},l=0;for(Ri.lastIndex=0;null!==(n=Ri.exec(t));){var u=new Jr(n[1],i),c=u.TYPE;if(c){var d=o[c],h=a[c]||[];a[c]=h;var f=u.LANGUAGE,v=u["ASSOC-LANGUAGE"],g=u.CHANNELS,p=u.CHARACTERISTICS,m=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?e.resolve(u.URI,r):""};if(v&&(y.assocLang=v),g&&(y.channels=g),p&&(y.characteristics=p),m&&(y.instreamId=m),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Ni(y,E,"audioCodec"),Ni(y,E,"textCodec")}h.push(y)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,r,i,n,a){var s,o,l,u,c,d={url:t},h=new ri(t),f=h.fragments,v=[],g=null,p=0,m=0,y=0,E=0,k=0,T=null,S=new Fe(i,d),b=-1,A=!1,L=null;if(Pi.lastIndex=0,h.m3u8=e,h.hasVariableRefs=Wr(e),"#EXTM3U"!==(null==(s=Pi.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=Pi.exec(e));){A&&(A=!1,(S=new Fe(i,d)).playlistOffset=y,S.setStart(y),S.sn=p,S.cc=E,k&&(S.bitrate=k),S.level=r,g&&(S.initSegment=g,g.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),L&&(S.setByteRange(L),L=null)));var I=o[1];if(I){S.duration=parseFloat(I);var R=(" "+o[2]).slice(1);S.title=R||null,S.tagList.push(R?["INF",I,R]:["INF",I])}else if(o[3]){if(X(S.duration)){S.playlistOffset=y,S.setStart(y),u&&Gi(S,u,h),S.sn=p,S.level=r,S.cc=E,f.push(S);var w=(" "+o[3]).slice(1);S.relurl=qr(h,w),Ui(S,T,v),T=S,y+=S.duration,p++,m=0,A=!0}}else{if(!(o=o[0].match(xi))){ke.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<o.length&&void 0===o[l];l++);var P=(" "+o[l]).slice(1),x=(" "+o[l+1]).slice(1),D=o[l+2]?(" "+o[l+2]).slice(1):null;switch(P){case"BYTERANGE":T?S.setByteRange(x,T):S.setByteRange(x);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=x,S.tagList.push(["PROGRAM-DATE-TIME",x]),-1===b&&(b=f.length);break;case"PLAYLIST-TYPE":h.type&&Hi(h,P,o),h.type=x.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Hi(h,P,o):f.length>0&&Vi(h,P,o),p=h.startSN=parseInt(x);break;case"SKIP":h.skippedSegments&&Hi(h,P,o);var C=new Jr(x,h),_=C.decimalInteger("SKIPPED-SEGMENTS");if(X(_)){h.skippedSegments+=_;for(var M=_;M--;)f.push(null);p+=_}var O=C.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(O.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&Hi(h,P,o),h.targetduration=Math.max(parseInt(x),1);break;case"VERSION":null!==h.version&&Hi(h,P,o),h.version=parseInt(x);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Hi(h,P,o),h.live=!1;break;case"#":(x||D)&&S.tagList.push(D?[x,D]:[x]);break;case"DISCONTINUITY":E++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([P]);break;case"BITRATE":S.tagList.push([P,x]),k=1e3*parseInt(x),X(k)?S.bitrate=k:k=0;break;case"DATERANGE":var F=new Jr(x,h),N=new ti(F,h.dateRanges[F.ID],h.dateRangeTagCount);h.dateRangeTagCount++,N.isValid||h.skippedSegments?h.dateRanges[N.id]=N:ke.warn('Ignoring invalid DATERANGE tag: "'.concat(x,'"')),S.tagList.push(["EXT-X-DATERANGE",x]);break;case"DEFINE":var U=new Jr(x,h);"IMPORT"in U?Xr(h,U,a):zr(h,U,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?Hi(h,P,o):f.length>0&&Vi(h,P,o),h.startCC=E=parseInt(x);break;case"KEY":var B=Mi(x,t,h);if(B.isSupported()){if("NONE"===B.method){u=void 0;break}u||(u={});var G=u[B.keyFormat];null!=G&&G.matches(B)||(G&&(u=de({},u)),u[B.keyFormat]=B)}else ke.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(x,'"'));break;case"START":h.startTimeOffset=Oi(x);break;case"MAP":var H=new Jr(x,h);if(S.duration){var V=new Fe(i,d);Bi(V,H,r,u),g=V,S.initSegment=g,g.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime)}else{var K=S.byteRangeEndOffset;if(K){var j=S.byteRangeStartOffset;L="".concat(K-j,"@").concat(j)}else L=null;Bi(S,H,r,u),g=S,A=!0}g.cc=E;break;case"SERVER-CONTROL":c&&Hi(h,P,o),c=new Jr(x),h.canBlockReload=c.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=c.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&c.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=c.optionalFloat("PART-HOLD-BACK",0),h.holdBack=c.optionalFloat("HOLD-BACK",0);break;case"PART-INF":h.partTarget&&Hi(h,P,o);var Y=new Jr(x);h.partTarget=Y.decimalFloatingPoint("PART-TARGET");break;case"PART":var W=h.partList;W||(W=h.partList=[]);var q=m>0?W[W.length-1]:void 0,z=m++,Q=new Jr(x,h),$=new Ne(Q,S,d,z,q);W.push($),S.duration+=$.duration;break;case"PRELOAD-HINT":var J=new Jr(x,h);h.preloadHint=J;break;case"RENDITION-REPORT":var Z=new Jr(x,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(Z);break;default:ke.warn("line parsed but not handled: ".concat(o))}}}T&&!T.relurl?(f.pop(),y-=T.duration,h.partList&&(h.fragmentHint=T)):h.partList&&(Ui(S,T,v),S.cc=E,h.fragmentHint=S,u&&Gi(S,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var ee=f.length,te=f[0],re=f[ee-1];if((y+=h.skippedSegments*h.targetduration)>0&&ee&&re){h.averagetargetduration=y/ee;var ie=re.sn;h.endSN="initSegment"!==ie?ie:0,h.live||(re.endList=!0),b>0&&(!function(e,t){for(var r=e[t],i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(f,b),te&&v.unshift(te))}return h.fragmentHint&&(y+=h.fragmentHint.duration),h.totalduration=y,v.length&&h.dateRangeTagCount&&te&&Ci(v,h),h.endCC=E,h}}])}();function Ci(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var c=r;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=_i(t,u,e,c,a);if(-1!==h){l.tagAnchor=t.fragments[h].ref;break}}}}function _i(e,t,r,i,n){var a=r[i];if(a){var s,o=a.programDateTime;if(t>=o||0===i)if(t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=r[i].sn-e.startSN;if(l<0)return-1;var u=e.fragments;if(u.length>r.length)for(var c=(r[i+1]||u[u.length-1]).sn-e.startSN;c>l;c--){var d=u[c].programDateTime;if(t>=d&&t<d+1e3*u[c].duration)return c}return l}}return-1}function Mi(e,t,r){var i,n,a=new Jr(e,r),s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&ke.error("Invalid IV: ".concat(a.IV));var d=o?Di.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Ai(s,d,c,h,l,a.KEYID)}function Oi(e){var t=new Jr(e).decimalFloatingPoint("TIME-OFFSET");return X(t)?t:null}function Fi(e,t){var r=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text"].forEach(function(e){var i=r.filter(function(t){return ft(t,e)});i.length&&(t["".concat(e,"Codec")]=i.map(function(e){return e.split("/")[0]}).join(","),r=r.filter(function(e){return-1===i.indexOf(e)}))}),t.unknownCodecs=r}function Ni(e,t,r){var i=t[r];i&&(e[r]=i)}function Ui(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Bi(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Gi(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||i.push(e)}function Hi(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(r[0],")"))}function Vi(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(r[0],")"))}function Ki(e,t){var r=t.startPTS;if(X(r)){var i,n=0;t.sn>e.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}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 ji(e,t,r,i,n,a,s){i-r<=0&&(s.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var o=r,l=i,u=t.startPTS,c=t.endPTS;if(X(u)){var d=Math.abs(u-r);e&&d>e.totalduration?s.warn("media timestamps and playlist times differ by ".concat(d,"s for level ").concat(t.level," ").concat(e.url)):X(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,o=Math.max(r,u),r=Math.min(r,u),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,l=Math.min(i,c),i=Math.max(i,c),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var h=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=o,t.startDTS=n,t.endPTS=i,t.minEndPTS=l,t.endDTS=a;var f,v=t.sn;if(!e||v<e.startSN||v>e.endSN)return 0;var g=v-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)Ki(p[f],p[f-1]);for(f=g;f<p.length-1;f++)Ki(p[f],p[f+1]);return e.fragmentHint&&Ki(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function Yi(e,t,r){if(e!==t){for(var i,n=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){n=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=n;u<=a;u++){var c=l[s+u],d=o[u];if(i&&!d&&c&&(d=t.fragments[u]=c),c&&d){r(c,d,u,o);var h=c.relurl,f=d.relurl;if(h&&en(h,f))return void(t.playlistParsingError=Wi("media sequence mismatch ".concat(d.sn,":"),e,t,c,d));if(c.cc!==d.cc)return void(t.playlistParsingError=Wi("discontinuity sequence mismatch (".concat(c.cc,"!=").concat(d.cc,")"),e,t,c,d))}}}(e,t,function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}X(e.startPTS)&&X(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(i=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)});var l=t.fragments,u=t.fragmentHint?l.concat(t.fragmentHint):l;if(n&&u.forEach(function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(function(e){return!e}),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var c=t.skippedSegments;c--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){var i=t.dateRanges,n=t.recentlyRemovedDateranges,a=de({},e);n&&n.forEach(function(e){delete a[e]});var s=Object.keys(a).length;if(!s)return i;return Object.keys(i).forEach(function(e){var t=a[e],n=new ti(i[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(Kt(i[e].attr),'"'))}),a}(e.dateRanges,t,r));var d=e.fragments.filter(function(e){return e.rawProgramDateTime});if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var h=1;h<u.length;h++)null===u[h].programDateTime&&Ui(u[h],u[h-1],d);Ci(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=Qi(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}!function(e,t,r){if(e&&t)for(var i=0,n=0,a=e.length;n<=a;n++){var s=e[n],o=t[n+i];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):i--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),i?ji(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):qi(e,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var g=t.advancedDateTime;if(t.advanced&&g){var p=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=p),t.driftEndTime=g,t.driftEnd=p}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Wi(e,t,r,i,n){return new Error("".concat(e," ").concat(n.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(r.startSN,"\n").concat(r.m3u8))}function qi(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,a=i>=0,s=0;if(a&&i<n.length)s=n[i].start;else if(a&&t.startSN===e.endSN+1)s=e.fragmentEnd;else if(a&&r)s=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;s=e.fragmentStart}zi(t,s)}function zi(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Xi(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var n=1e3*i[i.length-1].duration;n<r&&(r=n)}}else r/=2;return Math.round(r)}function Qi(e,t,r){if(!e)return null;var i=e.fragments[t-e.startSN];return i||((i=e.fragmentHint)&&i.sn===t?i:t<e.startSN&&r&&r.sn===t?r:null)}function $i(e,t,r){return e?Ji(e.partList,t,r):null}function Ji(e,t,r){if(e)for(var i=e.length;i--;){var n=e[i];if(n.index===r&&n.fragment.sn===t)return n}return null}function Zi(e){e.forEach(function(e,t){var r;null==(r=e.details)||r.fragments.forEach(function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function en(e,t){return!(e===t||!t)&&tn(e)!==tn(t)}function tn(e){return e.replace(/\?[^?]*$/,"")}function rn(e,t){for(var r=0,i=e.length;r<i;r++){var n;if((null==(n=e[r])?void 0:n.cc)===t)return e[r]}return null}function nn(e,t){var r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function an(e,t){for(var r=t.fragments,i=0,n=r.length;i<n;i++)nn(r[i],e);t.fragmentHint&&nn(t.fragmentHint,e),t.alignedSliding=!0}function sn(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var r=Math.min(t.endCC,e.endCC),i=rn(t.fragments,r),n=rn(e.fragments,r);if(i&&n)ke.log("Aligning playlist at start of dicontinuity sequence ".concat(r)),an(i.start-n.start,e)}}function on(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var r=e.fragments,i=t.fragments;if(r.length&&i.length){var n,a,s=Math.min(t.endCC,e.endCC);t.startCC<s&&e.startCC<s&&(n=rn(i,s),a=rn(r,s)),n&&a||(a=rn(r,(n=i[Math.floor(i.length/2)]).cc)||r[Math.floor(r.length/2)]);var o=n.programDateTime,l=a.programDateTime;if(o&&l)an((l-o)/1e3-(a.start-n.start),e)}}}function ln(e,t,r){un(e,t,r),e.addEventListener(t,r)}function un(e,t,r){e.removeEventListener(t,r)}var cn=function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="[".concat(e.start(i).toFixed(3),"-").concat(e.end(i).toFixed(3),"]");return t},dn="STOPPED",hn="IDLE",fn="KEY_LOADING",vn="FRAG_LOADING",gn="FRAG_LOADING_WAITING_RETRY",pn="WAITING_TRACK",mn="PARSING",yn="PARSED",En="ENDED",kn="ERROR",Tn="WAITING_INIT_PTS",Sn="WAITING_LEVEL",bn=function(e){function t(e,r,i,s,o){var l;return a(this,t),(l=n(this,t,[s,e.logger])).hls=void 0,l.fragPrevious=null,l.fragCurrent=null,l.fragmentTracker=void 0,l.transmuxer=null,l._state=dn,l.playlistType=void 0,l.media=null,l.mediaBuffer=null,l.config=void 0,l.bitrateTest=!1,l.lastCurrentTime=0,l.nextLoadPosition=0,l.startPosition=0,l.startTimeOffset=null,l.retryDate=0,l.levels=null,l.fragmentLoader=void 0,l.keyLoader=void 0,l.levelLastLoaded=null,l.startFragRequested=!1,l.decrypter=void 0,l.initPTS=[],l.buffering=!0,l.loadingParts=!1,l.loopSn=void 0,l.onMediaSeeking=function(){var e=l,t=e.config,r=e.fragCurrent,i=e.media,n=e.mediaBuffer,a=e.state,s=i?i.currentTime:0,o=jr.bufferInfo(n||i,s,t.maxBufferHole),u=!o.len;if(l.log("Media seeking to ".concat(X(s)?s.toFixed(3):s,", state: ").concat(a,", ").concat(u?"out of":"in"," buffer")),l.state===En)l.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(u||h<o.start||d>o.end){var f=s>h;(s<d||f)&&(f&&r.loader&&(l.log("Cancelling fragment load for seek (sn: ".concat(r.sn,")")),r.abortRequests(),l.resetLoadingState()),l.fragPrevious=null)}}if(i&&(l.fragmentTracker.removeFragmentsInRange(s,1/0,l.playlistType,!0),s>l.lastCurrentTime&&(l.lastCurrentTime=s),!l.loadingParts)){var v=Math.max(o.end,s),g=l.shouldLoadParts(l.getLevelDetails(),v);g&&(l.log("LL-Part loading ON after seeking to ".concat(s.toFixed(2)," with buffer @").concat(v.toFixed(2))),l.loadingParts=g)}l.hls.hasEnoughToStart||(l.log("Setting ".concat(u?"startPosition":"nextLoadPosition"," to ").concat(s," for seek without enough to start")),l.nextLoadPosition=s,u&&(l.startPosition=s)),u&&l.state===hn&&l.tickImmediate()},l.onMediaEnded=function(){l.log("setting startPosition to 0 because media ended"),l.startPosition=l.lastCurrentTime=0},l.playlistType=o,l.hls=e,l.fragmentLoader=new Nr(e.config),l.keyLoader=i,l.fragmentTracker=r,l.config=e.config,l.decrypter=new Or(e.config),l}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"doTick",value:function(){this.onTickEnd()}},{key:"onTickEnd",value:function(){}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){if(this.state!==dn){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var 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=dn}}},{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"pauseBuffering",value:function(){this.buffering=!1}},{key:"resumeBuffering",value:function(){this.buffering=!0}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"_streamEnded",value:function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=jr.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return jr.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}},{key:"getLevelDetails",value:function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"onMediaAttached",value:function(e,t){var r=this.media=this.mediaBuffer=t.media;ln(r,"seeking",this.onMediaSeeking),ln(r,"ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===dn&&this.startLoad(i.startPosition)}},{key:"onMediaDetaching",value:function(e,t){var r=!!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),un(i,"seeking",this.onMediaSeeking),un(i,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}},{key:"onManifestLoading",value:function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}},{key:"onError",value:function(e,t){}},{key:"onManifestLoaded",value:function(e,t){this.startTimeOffset=t.startTimeOffset}},{key:"onHandlerDestroying",value:function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),E(t,"onHandlerDestroying",this,3)([]),this.hls=this.onMediaSeeking=this.onMediaEnded=null}},{key:"onHandlerDestroyed",value:function(){this.state=dn,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,E(t,"onHandlerDestroyed",this,3)([])}},{key:"loadFragment",value:function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}},{key:"_loadFragForPlayback",value:function(e,t,r){var i=this;this._doFragLoad(e,t,r,function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(i.fragInfo(t,!1,e.part),") was dropped during download.")),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===vn||!i.fragCurrent&&t===mn)&&(i.fragmentTracker.removeFragment(r),i.state=hn):("payload"in e&&(i.log("Loaded ".concat(r.type," sn: ").concat(r.sn," of ").concat(i.playlistLabel()," ").concat(r.level)),i.hls.trigger(ee.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}}).catch(function(t){i.state!==dn&&i.state!==kn&&(i.warn("Frag error: ".concat((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,r=this.fragmentTracker;if(r.getState(e)===br){var i=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===Ar&&r.removeFragment(e))}},{key:"checkLiveUpdate",value:function(e){if(e.updated&&!e.live){var 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)}},{key:"waitForLive",value:function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}},{key:"flushMainBuffer",value:function(e,t){if(e-t){var r={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(ee.BUFFER_FLUSHING,r)}}},{key:"_loadInitSegment",value:function(e,t){var r=this;this._doFragLoad(e,t).then(function(e){var t=null==e?void 0:e.frag;if(!t||r.fragContextChanged(t)||!r.levels)throw new Error("init load aborted");return e}).then(function(e){var t=r.hls,i=e.frag,n=e.payload,a=i.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&ai(a.method)){var s=self.performance.now();return r.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,si(a.method)).catch(function(e){throw t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(function(n){var a=self.performance.now();return t.trigger(ee.FRAG_DECRYPTED,{frag:i,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,r.completeInitSegmentLoad(e)})}return r.completeInitSegmentLoad(e)}).catch(function(t){r.state!==dn&&r.state!==kn&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"completeInitSegmentLoad",value:function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==dn&&(this.state=hn),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()}},{key:"unhandledEncryptionError",value:function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in ".concat(this.fragInfo(t)," (media ").concat(a?"attached mediaKeys: "+a.mediaKeys:"detached",")"));return this.warn(s.message),!a||a.mediaKeys?!1:(this.hls.trigger(ee.ERROR,{type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}},{key:"fragContextChanged",value:function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level}},{key:"fragBufferedComplete",value:function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(r?cn(jr.getBuffered(r)):"(detached)",")")),Oe(e)){var i;if(e.type!==oe){var n=e.elementaryStreams;if(!Object.keys(n).some(function(e){return!!n[e]}))return void(this.state=hn)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(this.log("Resetting level fragment error count of ".concat(a.fragmentError," on frag buffered")),a.fragmentError=0)}this.state=hn}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some(function(e){return!e}),s=new Vr(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(s)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"_doFragLoad",value:function(e,t){var r,i=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3?arguments[3]:void 0;this.fragCurrent=e;var s=t.details;if(!this.levels||!s)throw new Error("frag load aborted, missing level".concat(s?"":" detail","s"));var o=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(o=this.keyLoader.loadClear(e,s.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");else if(this.log("Loading key for ".concat(e.sn," of [").concat(s.startSN,"-").concat(s.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=fn,this.fragCurrent=e,o=this.keyLoader.load(e).then(function(e){if(!i.fragContextChanged(e.frag))return i.hls.trigger(ee.KEY_LOADED,e),i.state===fn&&(i.state=hn),e}),this.hls.trigger(ee.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);var l,u=this.fragPrevious;if(Oe(e)&&(!u||e.sn!==u.sn)){var c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log("LL-Part loading ".concat(c?"ON":"OFF"," loading sn ").concat(null==u?void 0:u.sn,"->").concat(e.sn)),this.loadingParts=c)}if(n=Math.max(e.start,n||0),this.loadingParts&&Oe(e)){var d=s.partList;if(d&&a){n>s.fragmentEnd&&s.fragmentHint&&(e=s.fragmentHint);var h=this.getNextPart(d,e,n);if(h>-1){var f,v=d[h];return e=this.fragCurrent=v.fragment,this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(v.index," (").concat(h,"/").concat(d.length-1,") of ").concat(this.fragInfo(e,!1,v),") cc: ").concat(e.cc," [").concat(s.startSN,"-").concat(s.endSN,"], target: ").concat(parseFloat(n.toFixed(3)))),this.nextLoadPosition=v.start+v.duration,this.state=vn,f=o?o.then(function(r){return!r||i.fragContextChanged(r.frag)?null:i.doFragPartsLoad(e,v,t,a)}).catch(function(e){return i.handleFragLoadError(e)}):this.doFragPartsLoad(e,v,t,a).catch(function(e){return i.handleFragLoadError(e)}),this.hls.trigger(ee.FRAG_LOADING,{frag:e,part:v,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(d,n))return Promise.resolve(null)}}if(Oe(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(n.toFixed(2)," Check buffer at sn: ").concat(e.sn," loaded parts: ").concat(null==(l=s.partList)?void 0:l.filter(function(e){return e.loaded}).map(function(e){return"[".concat(e.start,"-").concat(e.end,"]")}))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1),") cc: ").concat(e.cc," ").concat("["+s.startSN+"-"+s.endSN+"]",", target: ").concat(parseFloat(n.toFixed(3)))),X(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=vn;var g,p=this.config.progressive;return g=p&&o?o.then(function(t){return!t||i.fragContextChanged(t.frag)?null:i.fragmentLoader.load(e,a)}).catch(function(e){return i.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,p?a:void 0),o]).then(function(e){var t=m(e,1)[0];return!p&&a&&a(t),t}).catch(function(e){return i.handleFragLoadError(e)}),this.hls.trigger(ee.FRAG_LOADING,{frag:e,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g}},{key:"doFragPartsLoad",value:function(e,t,r,i){var n=this;return new Promise(function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,c=function(t){n.fragmentLoader.loadPart(e,t,i).then(function(i){l[t.index]=i;var s=i.part;n.hls.trigger(ee.FRAG_LOADED,i);var o=$i(r.details,e.sn,t.index+1)||Ji(u,e.sn,t.index+1);if(!o)return a({frag:e,part:s,partsLoaded:l});c(o)}).catch(s)};c(t)})}},{key:"handleFragLoadError",value:function(e){if("data"in e){var t=e.data;t.frag&&t.details===Z.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===J.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(ee.ERROR,t)}else this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}},{key:"_handleTransmuxerFlush",value:function(e){var t=this.getCurrentContext(e);if(t&&this.state===mn){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(r.end.toFixed(2))),this.loadingParts=o),this.updateLevelTiming(r,i,n,e.partial)}else this.fragCurrent||this.state===dn||this.state===kn||(this.state=hn)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r,i,n=e.partList[0];if(n.fragment.type===oe)return!1;if(t>=n.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0))if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment ".concat(n," of ").concat(this.playlistLabel()," ").concat(i,". The current chunk will not be buffered.")),null;var s=t[i],o=s.details,l=a>-1?$i(o,n,a):null,u=l?l.fragment:Qi(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,r,i,n){if(this.state===mn){var a=e.data1,s=e.data2,o=a;if(s&&(o=it(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(ee.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(jr.isBuffered(t,t.currentTime)){var r=t.currentTime,i=jr.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var r,i=this.getLoadPosition();if(!X(i))return null;var n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,r,i){var n=jr.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return jr.bufferInfo(e,t,s)}}return n}},{key:"getMaxBufferLength",value:function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)}},{key:"reduceMaxBufferLength",value:function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to ".concat(n,"s")),!0)}},{key:"getAppendedFrag",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ae,r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}},{key:"getNextFragment",value:function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=r[0].start,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: ".concat(i,", need: ").concat(l,")")),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;s&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);var c=this.hls.startPosition,d=this.hls.liveSyncPosition,h=o?(-1!==c&&c>=a?c:d)||o.start:e;this.log("Setting startPosition to ".concat(h," to match start frag at live edge. mainStart: ").concat(c," liveSyncPosition: ").concat(d," frag.start: ").concat(null==(u=o)?void 0:u.start)),this.startPosition=this.nextLoadPosition=h}}else e<=a&&(o=r[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var v=this.filterReplacedPrimary(o,t);if(!v&&o){var g=o.sn-t.startSN;v=this.filterReplacedPrimary(r[g+1]||null,t)}return this.mapToInitFragWhenRequired(v)}},{key:"isLoopLoading",value:function(e,t){var r=this.fragmentTracker.getState(e);return(r===Lr||r===Ar&&!!e.gap)&&this.nextLoadPosition>t}},{key:"getNextFragmentLoopLoading",value:function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(i,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(An(this.config)&&(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))return!0;return!1}},{key:"filterReplacedPrimary",value:function(e,t){if(!e)return e;if(An(this.config)&&e.type!==oe){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||0===i.start)return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}}var a=null==r?void 0:r.playerQueue;if(a)for(var s=a.length;s--;){var o=a[s].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}},{key:"mapToInitFragWhenRequired",value:function(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}},{key:"getNextPart",value:function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,i>-1&&r<l.start)break;var u=l.loaded;u?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn("Need buffer at ".concat(r," but next unloaded part starts at ").concat(l.start)),i=s),n=u}return i}},{key:"loadedEndOfParts",value:function(e,t){for(var r,i=e.length;i--;){if(!(r=e[i]).loaded)return!1;if(t>r.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(r.programDateTime)),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!X(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i<e.length;++i){var n=e[i];if(rr(t,r,n))return n}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(i.sn)))}i||(i=ir(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}},{key:"getFragmentAtPosition",value:function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,c=a.maxFragLookUpTolerance,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&u);(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),e<t)?i=er(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:c):i=o[o.length-1];if(i){var f=i.sn-r.startSN,v=this.fragmentTracker.getState(i);if((v===Lr||v===Ar&&i.gap)&&(s=i),s&&i.sn===s.sn&&(!h||d[0].fragment.sn>i.sn||!r.live))if(i.level===s.level){var g=o[f+1];i=i.sn<l&&this.fragmentTracker.getState(g)!==Lr?g:null}}return i}},{key:"alignPlaylists",value:function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,a=!t,s=e.alignedSliding&&X(n);if(a||!s&&!n){!function(e,t){e&&(sn(t,e),t.alignedSliding||on(t,e),t.alignedSliding||t.skippedSegments||qi(e,t,!1))}(r,e);var o=e.fragmentStart;return this.log("Live playlist sliding: ".concat(o.toFixed(2)," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(i)),o}return n}},{key:"waitForCdnTuneIn",value:function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}},{key:"setStartPosition",value:function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;null!==a&&X(a)?(r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to ".concat(r," for start time offset ").concat(a," found in ").concat(n?"multivariant":"media"," playlist")),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge ".concat(r)),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+i}this.nextLoadPosition=r+i}},{key:"getLoadPosition",value:function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}},{key:"handleFragLoadAborted",value:function(e,t){this.transmuxer&&e.type===this.playlistType&&Oe(e)&&e.stats.aborted&&(this.log("Fragment ".concat(e.sn).concat(t?" part "+t.index:""," of ").concat(this.playlistLabel()," ").concat(e.level," was aborted")),this.resetFragmentLoading(e))}},{key:"resetFragmentLoading",value:function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===gn)||(this.state=hn)}},{key:"onFragmentOrKeyLoadError",value:function(e,t){var r;if(t.chunkMeta&&!t.frag){var i=this.getCurrentContext(t.chunkMeta);i&&(t.frag=i.frag)}var n=t.frag;if(n&&n.type===e&&this.levels)if(this.fragContextChanged(n)){var a;this.warn("Frag load error must match current frag to retry ".concat(n.url," > ").concat(null==(a=this.fragCurrent)?void 0:a.url))}else{var s=t.details===Z.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);var o=t.errorAction;if(o){var l=o.action,u=o.flags,c=o.retryCount,d=void 0===c?0:c,h=o.retryConfig,f=!!h,v=f&&l===gr,g=f&&!o.resolved&&u===mr,p=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!v&&g&&Oe(n)&&!n.endList&&p&&!sr(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var m,y=dr(null==(m=t.response)?void 0:m.code),E=lr(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=gn,o.resolved=!0,y)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment ".concat(n.sn," of ").concat(e," ").concat(n.level," errored with ").concat(t.details,", retrying loading ").concat(d+1,"/").concat(h.maxNumRetry," in ").concat(E,"ms"))}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn("".concat(t.details," reached or exceeded max retry (").concat(d,")"));s||l===vr||(o.resolved=!0)}else this.state=l===fr?Sn:kn;this.tickImmediate()}else this.state=kn}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!dr(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=hn)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===mn||this.state===yn){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a&&this.warn("Buffer full error while media.currentTime (".concat(this.getLoadPosition(),") is not buffered, flush ").concat(r," buffer")),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}},{key:"resetFragmentErrors",value:function(e){e===se&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==dn&&(this.state=hn)}},{key:"afterBufferFlushed",value:function(e,t,r){if(e){var i=jr.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===En&&this.resetLoadingState()}}},{key:"resetLoadingState",value:function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==dn&&(this.state=hn)}},{key:"resetStartWhenNotLoaded",value:function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var 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}}},{key:"resetWhenMissingContext",value:function(e){this.log("Loading context changed while buffering sn ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(-1===e.level?"<removed>":e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}},{key:"removeUnbufferedFrags",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}},{key:"updateLevelTiming",value:function(e,t,r,i){var n=this,a=r.details;if(a){var s;if(!Object.keys(e.elementaryStreams).reduce(function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment ".concat(e.sn," ").concat(s," duration reliably (").concat(l,")")),t||!1;var u=i?0:ji(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n);return n.hls.trigger(ee.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1))if(0===r.fragmentError&&this.treatAsGap(e,r),null===(null==(s=this.transmuxer)?void 0:s.error)){var o=new Error("Found no media in fragment ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(e.level," resetting transmuxer to fallback to playlist timing"));if(this.warn(o.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(r.url,'"')}),!this.hls)return;this.resetTransmuxer()}this.state=yn,this.log("Parsed ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t),")")),this.hls.trigger(ee.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")}},{key:"playlistLabel",value:function(){return this.playlistType===ae?"level":"track"}},{key:"fragInfo",value:function(e){var t,r,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(n?"part":"frag",":[").concat((null!=(t=i&&!n?e.startPTS:(n||e).start)?t:NaN).toFixed(3),"-").concat((null!=(r=i&&!n?e.endPTS:(n||e).end)?r:NaN).toFixed(3),"]").concat(n&&"main"===e.type?"INDEPENDENT="+(n.independent?"YES":"NO"):"")}},{key:"treatAsGap",value:function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}},{key:"resetTransmuxer",value:function(){var e;null==(e=this.transmuxer)||e.reset()}},{key:"recoverWorkerError",value:function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log("".concat(t,"->").concat(e)))}}])}(Hr);function An(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var Ln=function(){return o(function e(){a(this,e),this.chunks=[],this.dataLength=0},[{key:"push",value:function(e){this.chunks.push(e),this.dataLength+=e.length}},{key:"flush",value:function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n<e.length;n++){var a=e[n];r.set(a,i),i+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)}},{key:"reset",value:function(){this.chunks.length=0,this.dataLength=0}}])}();var In,Rn={exports:{}};var wn=(In||(In=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,i,a,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,a||e,s),l=r?r+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 s(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__||(r=!1)),o.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,s=new Array(a);n<a;n++)s[n]=i[n].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,n,a,s){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,n),!0;case 5:return c.fn.call(c.context,t,i,n,a),!0;case 6:return c.fn.call(c.context,t,i,n,a,s),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,i);break;case 4:c[u].fn.call(c[u].context,t,i,n);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return a(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,n){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn!==t||n&&!o.once||i&&o.context!==i||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||n&&!o[l].once||i&&o[l].context!==i)&&u.push(o[l]);u.length?this._events[a]=1===u.length?u[0]:u:s(this,a)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Rn)),Rn.exports),Pn=Ie(wn),xn="1.6.14",Dn={};function Cn(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 _n(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 Mn(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}function On(e,t){for(var r=t,i=0;_n(e,t);){i+=10,i+=Mn(e,t+6),Cn(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)}function Fn(e,t){return 255===e[t]&&240==(246&e[t+1])}function Nn(e,t){return 1&e[t+1]?7:9}function Un(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Bn(e,t){return t+1<e.length&&Fn(e,t)}function Gn(e,t){if(Bn(e,t)){var r=Nn(e,t);if(t+r>=e.length)return!1;var i=Un(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||Bn(e,n)}return!1}function Hn(e,t,r,i,n){if(!e.samplerate){var a=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s=1+(n>>6&3),o=t[r+3]>>6&3|(1&n)<<2,l="mp4a.40."+s,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;5!==s&&29!==s||(c-=3);var d=[s<<3|(14&c)>>1,(1&c)<<7|o<<3];return ke.log("manifest codec:".concat(i,", parsed codec:").concat(l,", channels:").concat(o,", rate:").concat(u," (ADTS object type:").concat(s," sampling index:").concat(a,")")),{config:d,samplerate:u,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}var h=new Error("invalid ADTS sampling index:".concat(a));e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!0,error:h,reason:h.message})}(t,r,i,n);if(!a)return;de(e,a)}}function Vn(e){return 9216e4/e}function Kn(e,t,r,i,n){var a,s=i+n*Vn(e.samplerate),o=function(e,t){var r=Nn(e,t);if(t+r<=e.length){var i=Un(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,r+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-r;return(a=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}function jn(e,t){return _n(e,t)&&Mn(e,t+6)+10<=e.length-t}function Yn(e){return function(e,t,r,i){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);var s=(d=e,d&&d.buffer instanceof ArrayBuffer&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),o=(s+e.byteLength)/a,l=(s+t)/a,u=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(u+Math.max(r,0),o));var d;return new i(n,u,c-u)}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,Uint8Array)}function Wn(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=be(Yn(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o=be(Yn(e.data,3+r,a));return s="--\x3e"===i?be(Yn(e.data,4+r+a)):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+r+a)),t.mimeType=i,t.pictureType=n,t.description=o,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function qn(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=be(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=be(e.data.subarray(t),!0);t+=r.length+1;var i=be(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=be(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?Wn(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=be(e.data.subarray(t),!0);t+=r.length+1;var i=be(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=be(e.data.subarray(1));return{key:e.type,info:"",data:n}}}(e)}function zn(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Mn(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function Xn(e){for(var t=0,r=[];_n(e,t);){var i=Mn(e,t+6);e[t+5]>>6&1&&(t+=10);for(var n=(t+=10)+i;t+10<n;){var a=zn(e.subarray(t)),s=qn(a);s&&r.push(s),t+=a.size+10}Cn(e,t)&&(t+=10)}return r}function Qn(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function $n(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function Jn(e){for(var t=Xn(e),r=0;r<t.length;r++){var i=t[r];if(Qn(i))return $n(i)}}var Zn=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 ea(){return{type:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",id:-1,pid:-1,inputTimeScale:arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4,sequenceNumber:-1,samples:[],dropped:0}}var ta=function(){return o(function e(){a(this,e),this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null},[{key:"resetInitSegment",value:function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}},{key:"resetTimeStamp",value:function(e){this.initPTS=e,this.resetContiguity()}},{key:"resetContiguity",value:function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}},{key:"canParse",value:function(e,t){return!1}},{key:"appendFrame",value:function(e,t,r){}},{key:"demux",value:function(e,t){this.cachedData&&(e=it(this.cachedData,e),this.cachedData=null);var r,i=On(e,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?Jn(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&X(o))&&(this.basePTS=ra(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var u=this.appendFrame(a,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=n+=u.length):n=l}else jn(e,n)?(i=On(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY}),r=n+=i.length):n++;if(n===l&&r!==l){var c=e.slice(r);this.cachedData?this.cachedData=it(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:ea(),id3Track:s,textTrack:ea()}}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}},{key:"flush",value:function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:ea(),id3Track:this._id3Track,textTrack:ea()}}},{key:"destroy",value:function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}])}(),ra=function(e,t,r){return X(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},ia=null,na=[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],aa=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],sa=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],oa=[0,1,1,4];function la(e,t,r,i,n){if(!(r+24>t.length)){var a=ua(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function ua(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*na[14*(3===r?3-i:3===i?3:4)+n-1],u=aa[3*(3===r?0:2===r?1:2)+a],c=3===o?1:2,d=sa[r][i],h=oa[i],f=8*d*h,v=Math.floor(d*l/u+s)*h;if(null===ia){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ia=g?parseInt(g[1]):0}return!!ia&&ia<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:v,samplesPerFrame:f}}}function ca(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function da(e,t){return t+1<e.length&&ca(e,t)}function ha(e,t){if(t+1<e.length&&ca(e,t)){var r=ua(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=t+i;return n===e.length||da(e,n)}return!1}var fa=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t)).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){E(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Fn(e,t)&&Un(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){Hn(e,this.observer,t,r,e.manifestCodec);var i=Kn(e,t,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}}],[{key:"probe",value:function(e,t){if(!e)return!1;var r=On(e,0),i=(null==r?void 0:r.length)||0;if(ha(e,i))return!1;for(var n=e.length;i<n;i++)if(Gn(e,i))return t.log("ADTS sync word found !"),!0;return!1}}])}(ta),va=function(e,t){var r=0,i=5;t+=i;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,r=r?r<<o|n[0]:n[0],t+=1,i-=o}return r},ga=function(e){function t(e){var r;return a(this,t),(r=n(this,t)).observer=void 0,r.observer=e,r}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){E(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,r){var i=pa(e,t,r,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0);if(!t)return!1;var r=t.length;return 11===e[r]&&119===e[r+1]&&void 0!==Jn(t)&&va(e,r)<16}}])}(ta);function pa(e,t,r,i,n){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,v=7&t[r+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),p=i+n*(1536/s*9e4),m=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:m,pts:p}),l}var ma=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){E(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return ca(e,t)&&4<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){if(null!==this.basePTS)return la(e,t,r,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Jn(t)&&va(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(ha(e,r))return ke.log("MPEG Audio sync word found !"),!0;return!1}}])}(ta),ya=/\/emsg[-/]ID3/i,Ea=function(){return o(function e(t,r){a(this,e),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=r},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,r,i){var n=this.videoTrack=ea("video",1),a=this.audioTrack=ea("audio",1),s=this.txtTrack=ea("text",1);if(this.id3Track=ea("id3",1),this.timeOffset=0,null!=e&&e.byteLength){var o=Xe(e);if(o.video){var l=o.video,u=l.id,c=l.timescale,d=l.codec,h=l.supplemental;n.id=u,n.timescale=s.timescale=c,n.codec=d,n.supplemental=h}if(o.audio){var f=o.audio,v=f.id,g=f.timescale,p=f.codec;a.id=v,a.timescale=g,a.codec=p}s.id=He.text,n.sampleDuration=0,n.duration=a.duration=i}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=it(this.remainderData,e));var a=function(e){var t={valid:null,remainder:null},r=qe(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,t);return n.samples=nt(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}},{key:"flush",value:function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=nt(e,t),{videoTrack:t,audioTrack:ea(),id3Track:i,textTrack:ea()}}},{key:"extractID3Track",value:function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var n=qe(e.samples,["emsg"]);n&&n.forEach(function(e){var n=function(e){var t=e[0],r="",i="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==Ve(e.subarray(u,u+1));)r+=Ve(e.subarray(u,u+1)),u+=1;for(r+=Ve(e.subarray(u,u+1)),u+=1;"\0"!==Ve(e.subarray(u,u+1));)i+=Ve(e.subarray(u,u+1)),u+=1;i+=Ve(e.subarray(u,u+1)),u+=1,n=je(e,12),a=je(e,16),o=je(e,20),l=je(e,24),u=28}else if(1===t){n=je(e,u+=4);var c=je(e,u+=4),d=je(e,u+=4);for(u+=4,s=Math.pow(2,32)*c+d,Q(s)||(s=Number.MAX_SAFE_INTEGER,ke.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=je(e,u),l=je(e,u+=4),u+=4;"\0"!==Ve(e.subarray(u,u+1));)r+=Ve(e.subarray(u,u+1)),u+=1;for(r+=Ve(e.subarray(u,u+1)),u+=1;"\0"!==Ve(e.subarray(u,u+1));)i+=Ve(e.subarray(u,u+1)),u+=1;i+=Ve(e.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(ya.test(n.schemeIdUri)){var a=ka(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Zn.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=ka(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Zn.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{key:"destroy",value:function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}],[{key:"probe",value:function(e){return function(e){for(var t=e.byteLength,r=0;r<t;){var i=je(e,r);if(i>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)}}])}();function ka(e,t){return X(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Ta=function(){return o(function e(t,r,i){a(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Or(r,{removePKCS7Padding:!1})},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,xr)}},{key:"decryptAacSample",value:function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then(function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}).catch(r)}}},{key:"decryptAacSamples",value:function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var r=new Uint8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)e.set(r.subarray(i,i+16),n);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,n){var a=this,s=lt(n.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then(function(o){n.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,i)}).catch(i)}},{key:"decryptAvcSamples",value:function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}}}])}(),Sa=function(){return o(function e(){a(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,r){var i,n,a=t.byteLength,s=e.naluState||0,o=s,l=[],u=0,c=-1,d=0;for(-1===s&&(c=0,d=this.getNALuType(t,0),s=0,u=1);u<a;)if(i=t[u++],s)if(1!==s)if(i)if(1===i){if(n=u-s-1,c>=0){var h={data:t.subarray(c,n),type:d};l.push(h)}else{var f=this.getLastNalUnit(e.samples);f&&(o&&u<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),n>0&&(f.data=it(f.data,t.subarray(0,n)),f.state=0))}u<a?(c=u,d=this.getNALuType(t,u),s=0):s=-1}else s=0;else s=3;else s=i?0:2;else s=i?0:1;if(c>=0&&s>=0){var v={data:t.subarray(c,a),type:d,state:s};l.push(v)}if(0===l.length){var g=this.getLastNalUnit(e.samples);g&&(g.data=it(g.data,t))}return e.naluState=s,l}}])}(),ba=function(){return o(function e(t){a(this,e),this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0},[{key:"loadWord",value:function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}},{key:"skipBits",value:function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&ke.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)>0&&this.bitsAvailable?r<<t|this.readBits(t):r}},{key:"skipLZ",value:function(){var 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()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}}])}(),Aa=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(function(i){var s,u;switch(i.type){case 1:var c=!1;n=!0;var d,h=i.data;if(l&&h.length>4){var f=a.readSliceType(h);2!==f&&4!==f&&7!==f&&9!==f||(c=!0)}if(c)null!=(d=o)&&d.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.frame=!0,o.key=c;break;case 5:n=!0,null!=(s=o)&&s.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,ot(i.data,1,r.pts,t.samples);break;case 7:var v,g;n=!0,l=!0;var p=i.data,m=a.readSPS(p);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(v=e.pixelRatio)?void 0:v[0])!==m.pixelRatio[0]||(null==(g=e.pixelRatio)?void 0:g[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[p];for(var y=p.subarray(1,4),E="avc1.",k=0;k<3;k++){var T=y[k].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(u=o)&&u.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"getNALuType",value:function(e,t){return 31&e[t]}},{key:"readSliceType",value:function(e){var t=new ba(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,n=0;n<e;n++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i}},{key:"readSPS",value:function(e){var t,r,i,n=new ba(e),a=0,s=0,o=0,l=0,u=n.readUByte.bind(n),c=n.readBits.bind(n),d=n.readUEG.bind(n),h=n.readBoolean.bind(n),f=n.skipBits.bind(n),v=n.skipEG.bind(n),g=n.skipUEG.bind(n),p=this.skipScalingList.bind(this);u();var m=u();if(c(5),f(3),u(),g(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),g(),g(),f(1),h())for(r=3!==y?8:12,i=0;i<r;i++)h()&&p(i<6?16:64,n)}g();var E=d();if(0===E)d();else if(1===E)for(f(1),v(),v(),t=d(),i=0;i<t;i++)v();g(),f(1);var k=d(),T=d(),S=c(1);0===S&&f(1),f(1),h()&&(a=d(),s=d(),o=d(),l=d());var b=[1,1];if(h()&&h())switch(u()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(k+1)-2*a-2*s),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}])}(Sa),La=function(e){function t(){var e;a(this,t);for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];return(e=n(this,t,[].concat(i))).initVPS=null,e}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(function(i){var s,u;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts)),o.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var c;if(n=!0,l)null!=(c=o)&&c.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:n=!0,null!=(s=o)&&s.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 39:n=!0,ot(i.data,2,r.pts,t.samples);break;case 32:n=!0,e.vps||("object"!==S(e.params)&&(e.params={}),e.params=de(e.params,a.readVPS(i.data)),a.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,l=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],i.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var d=a.readSPS(i.data);for(var h in e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],"object"!==S(e.params)&&(e.params={}),d.params)e.params[h]=d.params[h]}a.pushParameterSet(e.sps,i.data,e.vps),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0;break;case 34:if(n=!0,"object"===S(e.params)){if(!e.pps){e.pps=[];var f=a.readPPS(i.data);for(var v in f)e.params[v]=f[v]}a.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(u=o)&&u.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts));break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}},{key:"getNALuType",value:function(e,t){return(126&e[t])>>>1}},{key:"ebsp2rbsp",value:function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)}},{key:"pushAccessUnit",value:function(e,r){E(t,"pushAccessUnit",this,3)([e,r]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new ba(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}},{key:"readSPS",value:function(e){var t=new ba(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),v=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=[],y=[],E=0;E<r;E++)m.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(var k=r;k<8;k++)t.readBits(2);for(var T=0;T<r;T++)m[T]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[T]&&t.readUByte();t.readUEG();var S=t.readUEG();3==S&&t.skipBits(1);var b=t.readUEG(),A=t.readUEG(),L=t.readBoolean(),I=0,R=0,w=0,P=0;L&&(I+=t.readUEG(),R+=t.readUEG(),w+=t.readUEG(),P+=t.readUEG());for(var x=t.readUEG(),D=t.readUEG(),C=t.readUEG(),_=t.readBoolean()?0:r;_<=r;_++)t.skipUEG(),t.skipUEG(),t.skipUEG();if((t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean())&&t.readBoolean())for(var M=0;M<4;M++)for(var O=0;O<(3===M?2:6);O++){if(t.readBoolean()){var F=Math.min(64,1<<4+(M<<1));M>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var U=t.readUEG(),B=0,G=0;G<U;G++){var H=!1;if(0!==G&&(H=t.readBoolean()),H){G===U&&t.readUEG(),t.readBoolean(),t.readUEG();for(var V=0,K=0;K<=B;K++){var j=t.readBoolean(),Y=!1;j||(Y=t.readBoolean()),(j||Y)&&V++}B=V}else{var W=t.readUEG(),q=t.readUEG();B=W+q;for(var z=0;z<W;z++)t.readUEG(),t.readBoolean();for(var X=0;X<q;X++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var Q=t.readUEG(),$=0;$<Q;$++){for(var J=0;J<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,re=!0,ie=1,ne=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean())t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte());if(t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean())if(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean()){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var ce=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():ce=t.readBoolean();var de=ce?1:t.readUEG()+1;if(se)for(var he=0;he<de;he++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ve=b,ge=A;if(L){var pe=1,me=1;1===S?pe=me=2:2==S&&(pe=2),ve=b-pe*R-pe*I,ge=A-me*P-me*w}for(var ye=i?["A","B","C"][i]:"",Ee=s<<24|o<<16|l<<8|u,ke=0,Te=0;Te<32;Te++)ke=(ke|(Ee>>Te&1)<<31-Te)>>>0;var Se=ke.toString(16);1===a&&"2"===Se&&(Se="6");var be=n?"H":"L";return{codecString:"hvc1.".concat(ye).concat(a,".").concat(Se,".").concat(be).concat(p,".B0"),params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:p,bit_depth:x+8,bit_depth_luma_minus8:x,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:Z,chroma_format_idc:S,frame_rate:{fixed:re,fps:ne/ie}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new ba(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}}},{key:"matchSPS",value:function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}])}(Sa),Ia=188,Ra=function(){function e(t,r,i,n){a(this,e),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=t,this.config=r,this.typeSupported=i,this.logger=n,this.videoParser=null}return o(e,[{key:"resetInitSegment",value:function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n||(this.sampleAes=null);var s=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,c=s.pid,d=s.pesData,h=o.pid,f=l.pid,v=o.pesData,g=l.pesData,p=null,m=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=it(this.remainderData,t)).length,this.remainderData=null),E<Ia&&!a)return this.remainderData=t,{audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};var k=Math.max(0,e.syncOffset(t));(E-=(E-k)%Ia)<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,S=k;S<E;S+=Ia)if(71===t[S]){var b=!!(64&t[S+1]),A=wa(t,S),L=void 0;if((48&t[S+3])>>4>1){if((L=S+5+t[S+4])===S+Ia)continue}else L=S+4;switch(A){case c:b&&(d&&(i=_a(d,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,u,i,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(L,S+Ia)),d.size+=S+Ia-L);break;case h:if(b){if(v&&(i=_a(v,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i)}v={data:[],size:0}}v&&(v.data.push(t.subarray(L,S+Ia)),v.size+=S+Ia-L);break;case f:b&&(g&&(i=_a(g,this.logger))&&this.parseID3PES(l,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(L,S+Ia)),g.size+=S+Ia-L);break;case 0:b&&(L+=t[L]+1),y=this._pmtId=Pa(t,L);break;case y:b&&(L+=t[L]+1);var I=xa(t,L,this.typeSupported,n,this.observer,this.logger);(c=I.videoPid)>0&&(s.pid=c,s.segmentCodec=I.segmentVideoCodec),(h=I.audioPid)>0&&(o.pid=h,o.segmentCodec=I.segmentAudioCodec),(f=I.id3Pid)>0&&(l.pid=f),null===p||m||(this.logger.warn("MPEG-TS PMT found at ".concat(S," after unknown PID '").concat(p,"'. Backtracking to sync byte @").concat(k," to parse all TS packets.")),p=null,S=k-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=A}}else T++;T>0&&Da(this.observer,new Error("Found ".concat(T," TS packet/s that do not start with 0x47")),void 0,this.logger),s.pesData=d,o.pesData=v,l.pesData=g;var R={audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};return a&&this.extractRemainingSamples(R),R}},{key:"flush",value:function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}},{key:"extractRemainingSamples",value:function(e){var t,r=e.audioTrack,i=e.videoTrack,n=e.id3Track,a=e.textTrack,s=i.pesData,o=r.pesData,l=n.pesData;if(s&&(t=_a(s,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,a,t,!0),i.pesData=null)):i.pesData=s,o&&(t=_a(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t);break;case"ac3":this.parseAC3PES(r,t)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=_a(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l}},{key:"demuxSampleAes",value:function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new Ta(this.observer,this.config,t);return this.decrypt(i,n)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new Aa:"hevc"===e&&(this.videoParser=new La))}},{key:"decrypt",value:function(e,t){return new Promise(function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,function(){n.samples?t.decryptAvcSamples(n.samples,0,0,function(){r(e)}):r(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,function(){r(e)})})}},{key:"destroy",value:function(){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}},{key:"parseAACPES",value:function(e,t){var r,i,n,a=0,s=this.aacOverFlow,o=t.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(-1===l)o=it(s.sample.unit,o);else{var c=u-l;s.sample.unit.set(o.subarray(0,l),c),e.samples.push(s.sample),a=s.missing}}for(r=a,i=o.length;r<i-1&&!Bn(o,r);r++);if(r!==a){var d,h=r<i-1;if(d=h?"AAC PES did not start with ADTS header,offset:".concat(r):"No ADTS header found in AAC PES",Da(this.observer,new Error(d),h,this.logger),!h)return}if(Hn(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)n=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=Vn(e.samplerate);n=s.sample.pts+f}for(var v,g=0;r<i;){if(r+=(v=Kn(e,o,r,n,g)).length,v.missing){this.aacOverFlow=v;break}for(g++;r<i-1&&!Bn(o,r);r++);}}},{key:"parseMPEGPES",value:function(e,t){var r=t.data,i=r.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<i;)if(da(r,a)){var o=la(e,r,a,s,n);if(!o)break;a+=o.length,n++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{key:"parseAC3PES",value:function(e,t){var r=t.data,i=t.pts;if(void 0!==i)for(var n,a=r.length,s=0,o=0;o<a&&(n=pa(e,r,o,i,s++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")}},{key:"parseID3PES",value:function(e,t){if(void 0!==t.pts){var r=de({},t,{type:this._videoTrack?Zn.emsg:Zn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}}],[{key:"probe",value:function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset ".concat(i)),-1!==i}},{key:"syncOffset",value:function(e){for(var t=e.length,r=Math.min(940,t-Ia)+1,i=0;i<r;){for(var n=!1,a=-1,s=0,o=i;o<t;o+=Ia){if(71!==e[o]||t-o!==Ia&&71!==e[o+Ia]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+18612,e.length-Ia)+1),n||(n=0===wa(e,o)),n&&s>1&&(0===a&&s>2||o+Ia>r))return a}i++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:He[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}}])}();function wa(e,t){return((31&e[t+1])<<8)+e[t+2]}function Pa(e,t){return(31&e[t+10])<<8|e[t+11]}function xa(e,t,r,i,n,a){var s={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;){var l=wa(e,t),u=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Ca("ADTS AAC",a);break}case 15:-1===s.audioPid&&(s.audioPid=l);break;case 21:-1===s.id3Pid&&(s.id3Pid=l);break;case 219:if(!i){Ca("H.264",a);break}case 27:-1===s.videoPid&&(s.videoPid=l);break;case 3:case 4:r.mpeg||r.mp3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Ca("AC-3",a);break}case 129:r.ac3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===s.audioPid&&u>0)for(var c=t+5,d=u;d>2;){if(106===e[c])!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=l,s.segmentAudioCodec="ac3");var h=e[c+1]+2;c+=h,d-=h}break;case 194:case 135:return Da(n,new Error("Unsupported EC-3 in M2TS found"),void 0,a),s;case 36:-1===s.videoPid&&(s.videoPid=l,s.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=u+5}return s}function Da(e,t,r,i){i.warn("parsing error: ".concat(t.message)),e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Ca(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function _a(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=it(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn("".concat(Math.round((a-s)/9e4),"s delta between PTS and DTS, align them")),a=s):s=a);var c=(n=r[8])+9;if(e.size<=c)return null;e.size-=c;for(var d=new Uint8Array(e.size),h=0,f=l.length;h<f;h++){var v=(r=l[h]).byteLength;if(c){if(c>v){c-=v;continue}r=r.subarray(c),v-=c,c=0}d.set(r,o),o+=v}return i&&(i-=n+3),{data:d,pts:a,dts:s,len:i}}return null}var Ma=function(){return o(function e(){a(this,e)},null,[{key:"getSilentFrame",value:function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}])}(),Oa=Math.pow(2,32)-1,Fa=function(){function e(){a(this,e)}return o(e,null,[{key:"init",value:function(){var t;for(t in e.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:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=a,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var s=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,s,l,s,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))}},{key:"box",value:function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var a=i.length,s=a;a--;)t+=i[a].byteLength;var o=new Uint8Array(t);for(o[0]=t>>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),a=0,t=8;a<s;a++)o.set(i[a],t),t+=i[a].byteLength;return o}},{key:"hdlr",value:function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var i=Math.floor(r/(Oa+1)),n=Math.floor(r%(Oa+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(Oa+1)),n=Math.floor(r%(Oa+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)}},{key:"sdtp",value:function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r<n.length;r++)i=n[r].flags,a[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return e.box(e.types.sdtp,a)}},{key:"stbl",value:function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}},{key:"avc1",value:function(t){var r,i,n,a=[],s=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,c=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}},{key:"esds",value:function(e){var 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].concat(k(t),[6,1,2]))}},{key:"audioStsd",value:function(e){var 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])}},{key:"mp4a",value:function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))}},{key:"mp3",value:function(t){return e.box(e.types[".mp3"],e.audioStsd(t))}},{key:"ac3",value:function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))}},{key:"stsd",value:function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===r&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===r&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(r,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(Oa+1)),o=Math.floor(i%(Oa+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(Oa+1)),s=Math.floor(r%(Oa+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,n,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(r+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<c;i++)a=(n=u[i]).duration,s=n.size,o=n.flags,l=n.cts,h.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,h)}},{key:"initSegment",value:function(t){e.types||e.init();var r=e.moov(t);return it(e.FTYP,r)}},{key:"hvc1",value:function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s<i.length;s+=1){a+=3;for(var o=0;o<i[s].length;o+=1)a+=2+i[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=i.length-1,c=0;c<i.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,i[c].length]),a),a+=3;for(var d=0;d<i[c].length;d+=1)l.set(new Uint8Array([i[c][d].length>>8,255&i[c][d].length]),a),a+=2,l.set(i[c][d],a),a+=i[c][d].length}var h=e.box(e.types.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],p=t.pixelRatio[1];return e.box(e.types.hvc1,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,f>>8&255,255&f,v>>8&255,255&v,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]),h,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,255&g,p>>24,p>>16&255,p>>8&255,255&p])))}}])}();Fa.types=void 0,Fa.HDLR_TYPES=void 0,Fa.STTS=void 0,Fa.STSC=void 0,Fa.STCO=void 0,Fa.STSZ=void 0,Fa.VMHD=void 0,Fa.SMHD=void 0,Fa.STSD=void 0,Fa.FTYP=void 0,Fa.DINF=void 0;function Na(e,t){var r=e*t*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(r):r}function Ua(e){return Na(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function Ba(e){var t=e.baseTime,r=e.timescale,i=e.trackId;return"".concat(t/r," (").concat(t,"/").concat(r,") trackId: ").concat(i)}var Ga=null,Ha=null;function Va(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ka=function(e){function t(e,r,i,s){var o;if(a(this,t),(o=n(this,t,["mp4-remuxer",s])).observer=void 0,o.config=void 0,o.typeSupported=void 0,o.ISGenerated=!1,o._initPTS=null,o._initDTS=null,o.nextVideoTs=null,o.nextAudioTs=null,o.videoSampleDuration=null,o.isAudioContiguous=!1,o.isVideoContiguous=!1,o.videoTrackConfig=void 0,o.observer=e,o.config=r,o.typeSupported=i,o.ISGenerated=!1,null===Ga){var l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ga=l?parseInt(l[1]):0}if(null===Ha){var u=navigator.userAgent.match(/Safari\/(\d+)/i);Ha=u?parseInt(u[1]):0}return o}return d(t,e),o(t,[{key:"destroy",value:function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}},{key:"resetTimeStamp",value:function(e){var t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log("Reset initPTS: ".concat(t?Ba(t):t," > ").concat(e?Ba(e):e)),this._initPTS=this._initDTS=e}},{key:"resetNextTimestamp",value:function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}},{key:"resetInitSegment",value:function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}},{key:"getVideoStartPts",value:function(e){var t=!1,r=e[0].pts,i=e.reduce(function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=ja(n,r))-e),a>0?e:n},r);return t&&this.debug("PTS rollover detected"),i}},{key:"remux",value:function(e,t,r,i,n,a,s,o){var l,u,c,d,h,f,v=n,g=n,p=e.pid>-1,m=t.pid>-1,y=t.samples.length,E=e.samples.length>0,k=s&&y>0||y>1;if((!p||E)&&(!m||k)||this.ISGenerated||s){if(this.ISGenerated){var T,S,b,A,L=this.videoTrackConfig;(L&&(t.width!==L.width||t.height!==L.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(S=L.pixelRatio)?void 0:S[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(A=L.pixelRatio)?void 0:A[1]))||!L&&k||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));var I,R=this.isVideoContiguous,w=-1;if(k&&(w=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.warn("Dropped ".concat(w," out of ").concat(y," video samples due to a missing keyframe"));var P=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,I=g+=(t.samples[0].pts-P)/t.inputTimeScale}else-1===w&&(this.warn("No keyframe found out of ".concat(y," video samples")),f=!1);if(this.ISGenerated){if(E&&k){var x=this.getVideoStartPts(t.samples),D=(ja(e.samples[0].pts,x)-x)/t.inputTimeScale;v+=Math.max(0,D),g+=Math.max(0,-D)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,v,this.isAudioContiguous,a,m||k||o===se?g:void 0),k){var C=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,g,R,C)}}else k&&(l=this.remuxVideo(t,g,R,0));l&&(l.firstKeyFrame=w,l.independent=-1!==w,l.firstKeyFramePTS=I)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=Ya(r,n,this._initPTS,this._initDTS)),i.samples.length&&(d=Wa(i,n,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}},{key:"computeInitPts",value:function(e,t,r,i){var n=Math.round(r*t),a=ja(e,n);if(a<n+t)for(this.log("Adjusting PTS for rollover in timeline near ".concat((n-a)/t," ").concat(i));a<n+t;)a+=8589934592;return a-n}},{key:"generateIS",value:function(e,t,r,i){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||i,f="audio/mp4",v=-1;if(h&&(n=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}c.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):Fa.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(v=e.id,s=e.inputTimeScale,d&&s===d.timescale?h=!1:n=a=this.computeInitPts(o[0].pts,s,r,"audio"))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Fa.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(v=t.id,s=t.inputTimeScale,d&&s===d.timescale)h=!1;else{var g=this.getVideoStartPts(l),p=ja(l[0].dts,g),m=this.computeInitPts(p,s,r,"video"),y=this.computeInitPts(g,s,r,"video");a=Math.min(a,m),n=Math.min(n,y)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(d&&this.warn("Timestamps at playlist time: ".concat(i?"":"~").concat(r," ").concat(n/s," != initPTS: ").concat(d.baseTime/d.timescale," (").concat(d.baseTime,"/").concat(d.timescale,") trackId: ").concat(d.trackId)),this.log("Found initPTS at playlist time: ".concat(r," offset: ").concat(n/s," (").concat(n,"/").concat(s,") trackId: ").concat(v)),this._initPTS={baseTime:n,timescale:s,trackId:v},this._initDTS={baseTime:a,timescale:s,trackId:v}):n=s=void 0,{tracks:c,initPTS:n,timescale:s,trackId:v}}},{key:"remuxVideo",value:function(e,t,r,i){var n,a,s=e.inputTimeScale,o=e.samples,l=[],u=o.length,c=this._initPTS,d=c.baseTime*s/c.timescale,h=this.nextVideoTs,f=8,v=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===h){var y=d+t*s,E=o[0].pts-ja(o[0].dts,o[0].pts);Ga&&null!==h&&Math.abs(y-E-(h+d))<15e3?r=!0:h=y-E-d}for(var k=h+d,T=0;T<u;T++){var S=o[T];S.pts=ja(S.pts,k),S.dts=ja(S.dts,k),S.dts<o[T>0?T-1:T].dts&&(m=!0)}m&&o.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i}),n=o[0].dts;var b=(a=o[o.length-1].dts)-n,A=b?Math.round(b/(u-1)):v||e.inputTimeScale/30;if(r){var L=n-k,I=L>A,R=L<-1;if((I||R)&&(I?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ua(L,!0)," ms (").concat(L,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ua(-L,!0)," ms (").concat(L,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!R||k>=o[0].pts||Ga)){n=k;var w=o[0].pts-L;if(I)o[0].dts=n,o[0].pts=w;else for(var P=!0,x=0;x<o.length&&!(o[x].dts>w&&P);x++){var D=o[x].pts;if(o[x].dts-=L,o[x].pts-=L,x<o.length-1){var C=o[x+1].pts;P=C<=o[x].pts==C<=D}}this.log("Video: Initial PTS/DTS adjusted: ".concat(Ua(w,!0),"/").concat(Ua(n,!0),", delta: ").concat(Ua(L,!0)," ms"))}}for(var _=0,M=0,O=n=Math.max(0,n),F=0;F<u;F++){for(var N=o[F],U=N.units,B=U.length,G=0,H=0;H<B;H++)G+=U[H].data.length;M+=G,_+=B,N.length=G,N.dts<O?(N.dts=O,O+=A/4|0||1):O=N.dts,g=Math.min(N.pts,g),p=Math.max(N.pts,p)}a=o[u-1].dts;var V,K=M+4*_+8;try{V=new Uint8Array(K)}catch(e){return void this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MUX_ERROR,details:Z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:K,reason:"fail allocating video mdat ".concat(K)})}var j=new DataView(V.buffer);j.setUint32(0,K),V.set(Fa.types.mdat,4);for(var Y=!1,W=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<u;Q++){for(var $=o[Q],te=$.units,re=0,ie=0,ne=te.length;ie<ne;ie++){var ae=te[ie],se=ae.data,oe=ae.data.byteLength;j.setUint32(f,oe),f+=4,V.set(se,f),f+=oe,re+=4+oe}var le=void 0;if(Q<u-1)v=o[Q+1].dts-$.dts,le=o[Q+1].pts-$.pts;else{var ue=this.config,ce=Q>0?$.dts-o[Q-1].dts:A;if(le=Q>0?$.pts-o[Q-1].pts:A,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var he=Math.floor(ue.maxBufferHole*s),fe=(i?g+i*s:this.nextAudioTs+d)-$.pts;fe>he?((v=fe-ce)<0?v=ce:Y=!0,this.log("It is approximately ".concat(fe/90," ms to the next segment; using duration ").concat(v/90," ms for the last video frame."))):v=ce}else v=ce}var ve=Math.round($.pts-$.dts);W=Math.min(W,v),z=Math.max(z,v),q=Math.min(q,le),X=Math.max(X,le),l.push(Va($.key,v,re,ve))}if(l.length)if(Ga){if(Ga<70){var ge=l[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(Ha&&X-q<z-W&&A/z<.025&&0===l[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var pe=n,me=0,ye=l.length;me<ye;me++){var Ee=pe+l[me].duration,ke=pe+l[me].cts;if(me<ye-1){var Te=Ee+l[me+1].cts;l[me].duration=Te-ke}else l[me].duration=me?l[me-1].duration:A;l[me].cts=0,pe=Ee}}var Se=a+(v=Y||!v?A:v);this.nextVideoTs=h=Se-d,this.videoSampleDuration=v,this.isVideoContiguous=!0;var be={data1:Fa.moof(e.sequenceNumber++,n,de(e,{samples:l})),data2:V,startPTS:(g-d)/s,endPTS:(p+v-d)/s,startDTS:(n-d)/s,endDTS:h/s,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,be}},{key:"getSamplesPerFrame",value:function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}},{key:"remuxAudio",value:function(e,t,r,i,n){var a=e.inputTimeScale,s=a/(e.samplerate?e.samplerate:a),o=this.getSamplesPerFrame(e),l=o*s,u=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==n,f=e.samples,v=c?0:8,g=this.nextAudioTs||-1,p=u.baseTime*a/u.timescale,m=p+t*a;if(this.isAudioContiguous=r=r||f.length&&g>0&&(i&&Math.abs(m-(g+p))<9e3||Math.abs(ja(f[0].pts,m)-(g+p))<20*l),f.forEach(function(e){e.pts=ja(e.pts,m)}),!r||g<0){var y=f.length;if(f=f.filter(function(e){return e.pts>=0}),y!==f.length&&this.warn("Removed ".concat(f.length-y," of ").concat(y," samples (initPTS ").concat(p," / ").concat(a,")")),!f.length)return;g=0===n?0:i&&!h?Math.max(0,m-p):f[0].pts-p}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,k=0,T=g+p;k<f.length;k++){var S=f[k],b=S.pts,A=b-T,L=Math.abs(1e3*A/a);if(A<=-E*l&&h)0===k&&(this.warn("Audio frame @ ".concat((b/a).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*A/a)," ms.")),this.nextAudioTs=g=b-p,T=b);else if(A>=E*l&&L<1e4&&h){var I=Math.round(A/l);for(T=b-I*l;T<0&&I&&l;)I--,T+=l;0===k&&(this.nextAudioTs=g=T-p),this.warn("Injecting ".concat(I," audio frames @ ").concat(((T-p)/a).toFixed(3),"s due to ").concat(Math.round(1e3*A/a)," ms gap."));for(var R=0;R<I;R++){var w=Ma.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);w||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),w=S.unit.subarray()),f.splice(k,0,{unit:w,pts:T}),T+=l,k++}}S.pts=T,T+=l}for(var P,x=null,D=null,C=0,_=f.length;_--;)C+=f[_].unit.byteLength;for(var M=0,O=f.length;M<O;M++){var F=f[M],N=F.unit,U=F.pts;if(null!==D){d[M-1].duration=Math.round((U-D)/s)}else{if(r&&"aac"===e.segmentCodec&&(U=g+p),x=U,!(C>0))return;C+=v;try{P=new Uint8Array(C)}catch(e){return void this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MUX_ERROR,details:Z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:C,reason:"fail allocating audio mdat ".concat(C)})}c||(new DataView(P.buffer).setUint32(0,C),P.set(Fa.types.mdat,4))}P.set(N,v);var B=N.byteLength;v+=B,d.push(Va(!0,o,B,0)),D=U}var G=d.length;if(G){var H=d[d.length-1];g=D-p,this.nextAudioTs=g+s*H.duration;var V=c?new Uint8Array(0):Fa.moof(e.sequenceNumber++,x/s,de({},e,{samples:d}));e.samples=[];var K=(x-p)/a,j=g/a,Y={data1:V,data2:P,startPTS:K,endPTS:j,startDTS:K,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:G};return this.isAudioContiguous=!0,Y}}}])}(ve);function ja(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function Ya(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;s<n;s++){var o=e.samples[s];o.pts=ja(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=ja(o.dts-i.baseTime*a/i.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function Wa(e,t,r){var i=e.samples.length;if(i){for(var n=e.inputTimeScale,a=0;a<i;a++){var s=e.samples[a];s.pts=ja(s.pts-r.baseTime*n/r.timescale,t*n)/n}e.samples.sort(function(e,t){return e.pts-t.pts});var o=e.samples;return e.samples=[],{samples:o}}}var qa,za=function(e){function t(e,r,i,s){var o;return a(this,t),(o=n(this,t,["passthrough-remuxer",s])).emitInitSegment=!1,o.audioCodec=void 0,o.videoCodec=void 0,o.initData=void 0,o.initPTS=null,o.initTracks=void 0,o.lastEndTime=null,o.isVideoContiguous=!1,o}return d(t,e),o(t,[{key:"destroy",value:function(){}},{key:"resetTimeStamp",value:function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}},{key:"resetNextTimestamp",value:function(){this.isVideoContiguous=!1,this.lastEndTime=null}},{key:"resetInitSegment",value:function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,i),this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t){var r=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var n=this.initData=Xe(e),a=n.audio,s=n.video;if(t)!function(e,t){if(e&&t){var r=t.keyId;r&&t.isCommonEncryption&&tt(e,function(e,t){var i=e.subarray(8,24);i.some(function(e){return 0!==e})||(ke.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(Ae(i)," -> ").concat(Ae(r))),e.set(r,8))})}}(e,t);else{var o=a||s;null!=o&&o.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(o.codec,'")!'))}a&&(r=Qa(a,De,this)),s&&(i=Qa(s,Ce,this));var l={};a&&s?l.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:r,encrypted:a.encrypted,initSegment:e,id:"audio"}:s?l.video={container:"video/mp4",codec:i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}},{key:"remux",value:function(e,t,r,i,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,c={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};X(u)||(u=this.lastEndTime=n||0);var d=t.samples;if(!d.length)return c;var h={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if(null!=(s=f)&&s.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);var v=function(e,t,r){for(var i={},n=qe(e,["moof","traf"]),a=0;a<n.length;a++){var s=n[a],o=qe(s,["tfhd"])[0],l=je(o,4),u=t[l];if(u){i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:u.timescale,type:u.type});var c=i[l],d=qe(s,["tfdt"])[0];if(d){var h=d[0],f=je(d,4);1===h&&(f===Be?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=Be+1,f+=je(d,8))),X(f)&&(!X(c.start)||f<c.start)&&(c.start=f)}var v=u.default,g=je(o,0)|(null==v?void 0:v.flags),p=(null==v?void 0:v.duration)||0;8&g&&(p=je(o,2&g?12:8));for(var m=qe(s,["trun"]),y=c.start||0,E=0,k=p,T=0;T<m.length;T++){var S=m[T],b=je(S,4),A=c.sampleCount;c.sampleCount+=b;var L=1&S[3],I=4&S[3],R=1&S[2],w=2&S[2],P=4&S[2],x=8&S[2],D=8,C=b;for(L&&(D+=4),I&&b&&(1&S[D+1]||void 0!==c.keyFrameIndex||(c.keyFrameIndex=A),D+=4,R?(k=je(S,D),D+=4):k=p,w&&(D+=4),x&&(D+=4),y+=k,E+=k,C--);C--;)R?(k=je(S,D),D+=4):k=p,w&&(D+=4),P&&(1&S[D+1]||void 0===c.keyFrameIndex&&(c.keyFrameIndex=c.sampleCount-(C+1),c.keyFrameStart=y),D+=4),x&&(D+=4),y+=k,E+=k;!E&&p&&(E+=p*b)}c.duration+=E}}if(!Object.keys(i).some(function(e){return i[e].duration})){for(var _=1/0,M=0,O=qe(e,["sidx"]),F=0;F<O.length;F++){var N=ze(O[F]);if(null!=N&&N.references){_=Math.min(_,N.earliestPresentationTime/N.timescale);var U=N.references.reduce(function(e,t){return e+t.info.duration||0},0);M=Math.max(M,U+N.earliestPresentationTime/N.timescale)}}M&&X(M)&&Object.keys(i).forEach(function(e){i[e].duration||(i[e].duration=M*i[e].timescale-i[e].start)})}return i}(d,f,this),g=f.audio?v[f.audio.id]:null,p=f.video?v[f.video.id]:null,m=Xa(p,1/0),y=Xa(g,1/0),E=Xa(p,0,!0),k=Xa(g,0,!0),T=n,S=0,b=g&&(!p||!l&&y<m||l&&l.trackId===f.audio.id),A=b?g:p;if(A){var L=A.timescale,I=A.start-n*L,R=b?f.audio.id:f.video.id;T=A.start/L,S=b?k-y:E-m,!a&&l||!function(e,t,r,i){if(null===e)return!0;var n=Math.max(i,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>n}(l,T,n,S)&&L===l.timescale||(l&&this.warn("Timestamps at playlist time: ".concat(a?"":"~").concat(n," ").concat(I/L," != initPTS: ").concat(l.baseTime/l.timescale," (").concat(l.baseTime,"/").concat(l.timescale,") trackId: ").concat(l.trackId)),this.log("Found initPTS at playlist time: ".concat(n," offset: ").concat(T-n," (").concat(I,"/").concat(L,") trackId: ").concat(R)),l=null,h.initPTS=I,h.timescale=L,h.trackId=R)}else this.warn("No audio or video samples found for initPTS at playlist time: ".concat(n));l?(h.initPTS=l.baseTime,h.timescale=l.timescale,h.trackId=l.trackId):(h.timescale&&void 0!==h.trackId&&void 0!==h.initPTS||(this.warn("Could not set initPTS"),h.initPTS=T,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});var w=T-l.baseTime/l.timescale,P=w+S;S>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var x=!!f.audio,D=!!f.video,C="";x&&(C+="audio"),D&&(C+="video");var _={data1:d,startPTS:w,startDTS:w,endPTS:P,endDTS:P,type:C,hasAudio:x,hasVideo:D,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=x&&!D?_:void 0,c.video=D?_:void 0;var M=null==p?void 0:p.sampleCount;if(M){var O=p.keyFrameIndex,F=-1!==O;_.nb=M,_.dropped=0===O||this.isVideoContiguous?0:F?O:M,_.independent=F,_.firstKeyFrame=O,F&&p.keyFrameStart&&(_.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=F),this.isVideoContiguous||(this.isVideoContiguous=F),_.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(O,"/").concat(M," dropped: ").concat(_.dropped," start: ").concat(_.firstKeyFramePTS||"NA"))}return c.initSegment=h,c.id3=Ya(r,n,l,l),i.samples.length&&(c.text=Wa(i,n,l)),c}}])}(ve);function Xa(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Qa(e,t,r){var i=e.codec;if(i&&i.length>4)return i;if(t===De){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Tt(i,!1)}return r.warn('Unhandled audio codec "'.concat(i,'" in mp4 MAP')),i||"mp4a"}return r.warn('Unhandled video codec "'.concat(i,'" in mp4 MAP')),i||"avc1"}try{qa=self.performance.now.bind(self.performance)}catch(e){qa=Date.now}var $a=[{demux:Ea,remux:za},{demux:Ra,remux:Ka},{demux:fa,remux:Ka},{demux:ma,remux:Ka}];$a.splice(2,0,{demux:ga,remux:Ka});var Ja=function(){return o(function e(t,r,i,n,s,o){a(this,e),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=t,this.typeSupported=r,this.config=i,this.id=s,this.logger=o},[{key:"configure",value:function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}},{key:"push",value:function(e,t,r,i){var n=this,a=r.transmuxing;a.executeStart=qa();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,p=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,E=l.duration,k=l.initSegmentData,T=function(e,t){var r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(s,t);if(T&&ai(T.method)){var S=this.getDecrypter(),b=si(T.method);if(!S.isSync())return this.asyncResult=!0,this.decryptionPromise=S.webCryptoDecrypt(s,T.key.buffer,T.iv.buffer,b).then(function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t}),this.decryptionPromise;var A=S.softwareDecrypt(s,T.key.buffer,T.iv.buffer,b);if(r.part>-1){var L=S.flush();A=L?L.buffer:L}if(!A)return a.executeEnd=qa(),Za(r);s=new Uint8Array(A)}var I=this.needsProbing(d,h);if(I){var R=this.configureTransmuxer(s);if(R)return this.logger.warn("[transmuxer] ".concat(R.message)),this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),a.executeEnd=qa(),Za(r)}(d||h||g||I)&&this.resetInitSegment(k,p,m,E,t),(d||g||I)&&this.resetInitialTimestamp(y),c||this.resetContiguity();var w=this.transmux(s,T,v,f,r);this.asyncResult=es(w);var P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,a.executeEnd=qa(),w}},{key:"flush",value:function(e){var t=this,r=e.transmuxing;r.executeStart=qa();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then(function(){return t.flush(e)});var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){r.executeEnd=qa();var d=[Za(e)];return this.asyncResult?Promise.resolve(d):d}var h=u.flush(o);return es(h)?(this.asyncResult=!0,h.then(function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,r){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(r.sn).concat(r.part>-1?" part: "+r.part:""," of ").concat(this.id===ae?"level":"track"," ").concat(r.level));var c=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=qa()}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}},{key:"resetContiguity",value:function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}},{key:"resetInitSegment",value:function(e,t,r,i,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(e,t,r,i),s.resetInitSegment(e,t,r,n))}},{key:"destroy",value:function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}},{key:"transmux",value:function(e,t,r,i,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)}},{key:"transmuxUnencrypted",value:function(e,t,r,i){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),a=n.audioTrack,s=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,t,r,!1,this.id),chunkMeta:i}}},{key:"transmuxSampleAes",value:function(e,t,r,i,n){var a=this;return this.demuxer.demuxSampleAes(e,t,r).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id),chunkMeta:n}})}},{key:"configureTransmuxer",value:function(e){for(var t,r=this.config,i=this.observer,n=this.typeSupported,a=0,s=$a.length;a<s;a++){var o;if(null!=(o=$a[a].demux)&&o.probe(e,this.logger)){t=$a[a];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,c=t.remux,d=t.demux;u&&u instanceof c||(this.remuxer=new c(i,r,n,this.logger)),l&&l instanceof d||(this.demuxer=new d(i,r,n,this.logger),this.probe=d.probe)}},{key:"needsProbing",value:function(e,t){return!this.demuxer||!this.remuxer||e||t}},{key:"getDecrypter",value:function(){var e=this.decrypter;return e||(e=this.decrypter=new Or(this.config)),e}}])}();var Za=function(e){return{remuxResult:{},chunkMeta:e}};function es(e){return"then"in e&&e.then instanceof Function}var ts=o(function e(t,r,i,n,s){a(this,e),this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=i,this.duration=n,this.defaultInitPts=s||null}),rs=o(function e(t,r,i,n,s,o){a(this,e),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=t,this.contiguous=r,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}),is=0,ns=function(){return o(function e(t,r,i,n){var s=this;a(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=is++,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=function(e){var t=e.data,r=s.hls;if(r&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var i,n=null==(i=s.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=s.frag,t.data.part=s.part,t.data.id=s.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(s.hls){var t=new Error("".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")"));s.hls.config.enableWorker=!1,s.hls.logger.warn('Error in "'.concat(s.id,'" Web Worker, fallback to inline')),s.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var o=t.config;this.hls=t,this.id=r,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;var l=function(e,t){(t=t||{}).frag=s.frag||void 0,e===ee.ERROR&&(t.parent=s.id,t.part=s.part,s.error=t.error),s.hls.trigger(e,t)};this.observer=new Pn,this.observer.on(ee.FRAG_DECRYPTED,l),this.observer.on(ee.ERROR,l);var u=Lt(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var c=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(c.log("loading Web Worker ".concat(o.workerPath,' for "').concat(r,'"')),this.workerContext=function(e){var t=Dn[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Dn[e]=i,i}(o.workerPath)):(c.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=function(){var e=Dn[xn];if(e)return e.clientCount++,e;var t=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}),r=self.URL.createObjectURL(t),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return Dn[xn]=i,i}());var d=this.workerContext.worker;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:r,config:Kt(o)})}catch(e){c.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),e),this.terminateWorker(),this.error=null,this.transmuxer=new Ja(this.observer,u,o,"",r,t.logger)}return}}this.transmuxer=new Ja(this.observer,u,o,"",r,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=is++;var t=this.hls.config,r=Lt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Kt(t)})}}},{key:"terminateWorker",value:function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=Dn[e||xn];if(t&&1===t.clientCount--){var r=t.worker,i=t.objectURL;delete Dn[e||xn],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}}},{key:"destroy",value:function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}},{key:"push",value:function(e,t,r,i,n,a,s,o,l,u){var c,d,h=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,v=this.transmuxer,g=a?a.start:n.start,p=n.decryptdata,m=this.frag,y=!(m&&n.cc===m.cc),E=!(m&&l.level===m.level),k=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===k&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!E&&(1===k||0===k&&(1===T||S&&T<=0)),A=self.performance.now();(E||k||0===n.stats.parsing.start)&&(n.stats.parsing.start=A),!a||!T&&b||(a.stats.parsing.start=A);var L=!(m&&(null==(c=n.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),I=new rs(y,b,o,E,g,L);if(!b||y||L){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for ".concat(n.type," sn: ").concat(l.sn).concat(l.part>-1?" part: "+l.part:""," ").concat(this.id===ae?"level":"track",": ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(y,"\n trackSwitch: ").concat(E,"\n contiguous: ").concat(b,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(L));var R=new ts(r,i,t,s,u);this.configureTransmuxer(R)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(v){var w=v.push(e,p,l,I);es(w)?w.then(function(e){h.handleTransmuxComplete(e)}).catch(function(e){h.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}},{key:"flush",value:function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);es(n)?n.then(function(r){t.handleFlushResult(r,e)}).catch(function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}},{key:"transmuxerError",value:function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}},{key:"handleFlushResult",value:function(e,t){var r=this;e.forEach(function(e){r.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),as=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"audio-stream-controller",se])).mainAnchor=null,s.mainFragLoading=null,s.audioOnly=!1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s.registerListeners(),s}return d(t,e),o(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),E(t,"onHandlerDestroying",this,3)([]),this.resetItem()}},{key:"resetItem",value:function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}},{key:"registerListeners",value:function(){E(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ee.BUFFER_RESET,this.onBufferReset,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ee.FRAG_LOADING,this.onFragLoading,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(E(t,"unregisterListeners",this,3)([]),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ee.BUFFER_RESET,this.onBufferReset,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this))}},{key:"onInitPtsFound",value:function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId;if(i===ae){var o=r.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:a,trackId:s},this.log("InitPTS for cc: ".concat(o," found from main: ").concat(n/a," (").concat(n,"/").concat(a,") trackId: ").concat(s)),this.mainAnchor=r,this.state===Tn){var u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==o)&&this.syncWithAnchor(r,null==u?void 0:u.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(r,l)):this.state===hn&&this.tick()}}},{key:"getLoadPosition",value:function(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:E(t,"getLoadPosition",this,3)([])}},{key:"syncWithAnchor",value:function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=ir(this.getLevelDetails(),n,this.getLoadPosition());a&&(this.log("Syncing with main frag at ".concat(a.start," cc ").concat(a.cc)),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===hn&&this.doTickIdle())}}},{key:"startLoad",value:function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=dn);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r,this.state=hn):this.state=pn,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"doTick",value:function(){switch(this.state){case hn:this.doTickIdle();break;case pn:var e=this.levels,r=this.trackId,i=null==e?void 0:e[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=Tn}break;case gn:this.checkRetryDate();break;case Tn:var a=this.waitingData;if(a){var s=a.frag,o=a.part,l=a.cache,u=a.complete,c=this.mainAnchor;if(void 0!==this.initPTS[s.cc]){this.waitingData=null,this.state=vn;var d={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),u&&E(t,"_handleFragmentLoadComplete",this,3)([d])}else c&&c.cc!==a.frag.cc&&this.syncWithAnchor(c,a.frag)}else this.state=hn}this.onTickEnd()}},{key:"resetLoadingState",value:function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),E(t,"resetLoadingState",this,3)([])}},{key:"onTickEnd",value:function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}},{key:"doTickIdle",value:function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=pn,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,De,se));var u=this.getFwdBufferInfo(l,se);if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(ee.BUFFER_EOS,{type:"audio"}),void(this.state=En);var c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,v=this.getLoadPosition(),g=this.flushing?v:u.end;if(this.switchingTrack&&i){var p=v;o.PTSKnown&&p<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var m=this.getNextFragment(g,o);if(m&&this.isLoopLoading(m,g)&&(m=this.getNextFragmentLoopLoading(m,o,u,ae,d)),m){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Oe(m)&&!m.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Lr&&(this.mainFragLoading=y=null),y&&Oe(y))){if(m.start>y.end){var E=this.fragmentTracker.getFragAtPos(g,ae);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,s,g)}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(e,r){this.bufferFlushed=this.flushing=!1,E(t,"onMediaDetaching",this,3)([e,r])}},{key:"onAudioTracksUpdated",value:function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map(function(e){return new Gt(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==dn&&(this.setInterval(100),this.state=hn,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}},{key:"onManifestLoading",value:function(){E(t,"onManifestLoading",this,3)([]),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ee.AUDIO_TRACK_LOADED,r))}},{key:"onAudioTrackLoaded",value:function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==dn&&(this.state=pn));this.cachedTrackLoadedData=null,this.log("Audio track ".concat(a,' "').concat(o.name,'" of "').concat(s,'" loaded [').concat(n.startSN,",").concat(n.endSN,"]").concat(n.lastPartSn?"[part-".concat(n.lastPartSn,"-").concat(n.lastPartIndex,"]"):"",",duration:").concat(n.totalduration));var u=i[a],c=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(n,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);n.alignedSliding||(sn(n,l),n.alignedSliding||on(n,l),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(ee.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==pn||this.waitForCdnTuneIn(n)||(this.state=hn),this.tick()}else this.warn("Audio tracks reset while loading track ".concat(a,' "').concat(o.name,'" of "').concat(s,'"'))}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var c=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new ns(this.hls,se,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){var v=i?i.index:-1,g=-1!==v,p=new Vr(r.level,r.sn,r.stats.chunkCount,n.byteLength,v,g);d.push(n,f,c,"",r,i,u.totalduration,!1,p,h)}else{this.log("Unknown video PTS for cc ".concat(r.cc,", waiting for video PTS before demuxing audio frag ").concat(r.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new Ln,complete:!1}).cache.push(new Uint8Array(n)),this.state!==dn&&(this.state=Tn)}}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"_handleFragmentLoadComplete",value:function(e){this.waitingData?this.waitingData.complete=!0:E(t,"_handleFragmentLoadComplete",this,3)([e])}},{key:"onBufferReset",value:function(){this.mediaBuffer=null}},{key:"onBufferCreated",value:function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}},{key:"onFragLoading",value:function(e,t){!this.audioOnly&&t.frag.type===ae&&Oe(t.frag)&&(this.mainFragLoading=t,this.state===hn&&this.tick())}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part;if(r.type===se)if(this.fragContextChanged(r))this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if(Oe(r)){this.fragPrevious=r;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},n)))}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==ae||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"onError",value:function(e,r){var i;if(r.fatal)this.state=kn;else switch(r.details){case Z.FRAG_GAP:case Z.FRAG_PARSING_ERROR:case Z.FRAG_DECRYPT_ERROR:case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(se,r);break;case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==pn||(null==(i=r.context)?void 0:i.type)!==ie||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case Z.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,E(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]));break;case Z.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==Ce&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==Ce){this.flushing=!1,this.bufferFlushed=!0,this.state===En&&(this.state=hn);var i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,r,se),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var t,r="audio",i=this.hls,n=e.remuxResult,a=e.chunkMeta,s=this.getCurrentContext(a);if(s){var o=s.frag,l=s.part,u=s.level,c=u.details,d=n.audio,h=n.text,f=n.id3,v=n.initSegment;if(!this.fragContextChanged(o)&&c){if(this.state=mn,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){var g=o.initSegment||o;if(this.unhandledEncryptionError(v,o))return;this._bufferInitSegment(u,v.tracks,g,a),i.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:r,tracks:v.tracks})}if(d){var p=d.startPTS,m=d.endPTS,y=d.startDTS,E=d.endDTS;l&&(l.elementaryStreams[De]={startPTS:p,endPTS:m,startDTS:y,endDTS:E}),o.setElementaryStreamInfo(De,p,m,y,E),this.bufferFragmentData(d,o,l,a)}if(null!=f&&null!=(t=f.samples)&&t.length){var k=de({id:r,frag:o,details:c},f);i.trigger(ee.FRAG_PARSING_METADATA,k)}if(h){var T=de({id:r,frag:o,details:c},h);i.trigger(ee.FRAG_PARSING_USERDATA,T)}}else this.fragmentTracker.removeFragment(o)}else this.resetWhenMissingContext(a)}},{key:"_bufferInitSegment",value:function(e,t,r,i){if(this.state===mn&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=se;var a=e.audioCodec;this.log("Init audio buffer, container:".concat(n.container,", codecs[level/parsed]=[").concat(a,"/").concat(n.codec,"]")),a&&1===a.split(",").length&&(n.levelCodec=a),this.hls.trigger(ee.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(ee.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,r,i){var n,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===Sr||a===Ar)if(Oe(e))if(null!=(n=r.details)&&n.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter ".concat(e.cc," of live stream before loading audio fragment ").concat(e.sn," of level ").concat(this.trackId)),this.state=Tn;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&on(r.details,s)}else E(t,"loadFragment",this,3)([e,r,i]);else this._loadInitSegment(e,r);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack){var r=this.bufferedTrack;zt({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},e,Xt)||($t(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),E(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]),this.bufferedTrack=null):this.bufferedTrack=e)}}},{key:"completeAudioSwitch",value:function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},e))}}])}(bn),ss=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r,e.logger])).hls=void 0,i.canLoad=!1,i.timer=-1,i.hls=e,i}return d(t,e),o(t,[{key:"destroy",value:function(){this.clearTimer(),this.hls=this.log=this.warn=null}},{key:"clearTimer",value:function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}},{key:"startLoad",value:function(){this.canLoad=!0,this.loadPlaylist()}},{key:"stopLoad",value:function(){this.canLoad=!1,this.clearTimer()}},{key:"switchParams",value:function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a<i.length;a++){var s=i[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: ".concat(e)),o=s.URI||""}if(o===e){n=a;break}o===e.substring(0,o.length)&&(n=a)}if(-1!==n){var l=i[n],u=parseInt(l["LAST-MSN"])||t.lastPartSn,c=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}var h=r&&Ut(r);return new Bt(u,c>=0?c:void 0,h)}}}},{key:"loadPlaylist",value:function(e){this.clearTimer()}},{key:"loadingPlaylist",value:function(e,t){this.clearTimer()}},{key:"shouldLoadPlaylist",value:function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}},{key:"getUrlWithDirectives",value:function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(e))}return e}},{key:"playlistLoaded",value:function(e,t,r){var i=t.details,n=t.stats,a=self.performance.now(),s=n.loading.first?Math.max(0,a-n.loading.first):0;i.advancedDateTime=Date.now()-s;var o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){var l=Math.max(o||0,0);i.appliedTimelineOffset=l,i.fragments.forEach(function(e){e.setStart(e.playlistOffset+l)})}if(i.live||null!=r&&r.live){var u="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(r),r&&i.fragments.length>0){Yi(r,i,this);var c=i.playlistParsingError;if(c){this.warn(c);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var h,f=t.networkDetails;return void d.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:c,reason:c.message,level:t.level||void 0,parent:null==(h=i.fragments[0])?void 0:h.type,networkDetails:f,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var v,g=this.hls.mainForwardBufferInfo,p=g?g.end-g.len:0,m=Xi(i,1e3*(i.edge-p));if(i.requestScheduled+m<a?i.requestScheduled=a:i.requestScheduled+=m,this.log("live playlist ".concat(e," ").concat(i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED")),!this.canLoad||!i.live)return;var y=void 0,E=void 0;if(i.canBlockReload&&i.endSN&&i.advanced){var k=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,b=i.lastPartIndex,A=T===S;-1!==b?A?(y=S+1,E=k?0:b):(y=T,E=k?b+1:i.maxPartIndex):y=S+1;var L=i.age,I=L+i.ageHeader,R=Math.min(I-i.partTarget,1.5*i.targetduration);if(R>0){if(I>3*i.targetduration)this.log("Playlist last advanced ".concat(L.toFixed(2),"s ago. Omitting segment and part directives.")),y=void 0,E=void 0;else if(null!=r&&r.tuneInGoal&&I-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(r.tuneInGoal," to: ").concat(R," with playlist age: ").concat(i.age)),R=0;else{var w=Math.floor(R/i.targetduration);if(y+=w,void 0!==E)E+=Math.round(R%i.targetduration/i.partTarget);this.log("CDN Tune-in age: ".concat(i.ageHeader,"s last advanced ").concat(L.toFixed(2),"s goal: ").concat(R," skip sn ").concat(w," to part ").concat(E))}i.tuneInGoal=R}if(v=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),k||!A)return i.requestScheduled=a,void this.loadingPlaylist(u,v)}else(i.canBlockReload||i.canSkipUntil)&&(v=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));v&&void 0!==y&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(m-2*s,m/2)),this.scheduleLoading(u,v,i)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s)this.loadingPlaylist(e,t);else{var o=s-a;this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(function(){return i.loadingPlaylist(e,t)},o)}}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,r,i){var n=Ut(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=Ot),new Bt(r,i,n)}},{key:"checkRetry",value:function(e){var t=this,r=e.details,i=nr(e),n=e.errorAction,a=n||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,c=!!n&&!!u&&(s===gr||!n.resolved&&s===fr);if(c){var d;if(l>=u.maxNumRetry)return!1;if(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" without delivery-directives')),this.loadPlaylist();else{var h=lr(u,l);this.clearTimer(),this.timer=self.setTimeout(function(){return t.loadPlaylist()},h),this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" in ').concat(h,"ms"))}e.levelRetry=!0,n.resolved=!0}return c}}])}(ve);function os(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!ls(e[r].attrs,t[r].attrs))return!1;return!0}function ls(e,t,r){var i=e["STABLE-RENDITION-ID"];return i&&!r?i===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(r){return e[r]!==t[r]})}function us(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var cs=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e,"audio-track-controller"])).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,E(t,"destroy",this,3)([])}},{key:"onManifestLoading",value:function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.audioTracks||[]}},{key:"onAudioTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Audio track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.audioPreference;if(!n&&s){var o=qt(s,a,Xt);if(o>-1)n=a[o];else{var l=qt(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={audioTracks:a};this.log("Updating audio tracks, ".concat(a.length," track(s) found in group(s): ").concat(null==r?void 0:r.join(","))),this.hls.trigger(ee.AUDIO_TRACKS_UPDATED,c);var d=this.trackId;if(-1!==u&&-1===d)this.setAudioTrack(u);else if(a.length&&-1===d){var h,f=new Error("No audio track selected for current audio group-ID(s): ".concat(null==(h=this.groupIds)?void 0:h.join(",")," track count: ").concat(a.length));this.warn(f.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&(t.context.type!==ie||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}},{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}},{key:"setAudioOption",value:function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&zt(e,i,Xt))return i;var n=qt(e,this.tracksInGroup,Xt);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce(function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e},{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),c=Qt(t,i,function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter(function(e){return!i||-1!==i.indexOf(e.groupId)});return qt(e,a,n)>-1});return c>-1?c:Qt(t,i,function(t){var i=t.audioGroups,a=r.filter(function(e){return!i||-1!==i.indexOf(e.groupId)});return qt(e,a,n)>-1})}(e,t.levels,r,s,Xt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=qt(e,r);if(l>-1)return r[l]}}}return null}},{key:"setAudioTrack",value:function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: ".concat(e));else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e],n=i.details&&!i.details.live;if(!(e===this.trackId&&i===r&&n||(this.log("Switching to audio-track ".concat(e,' "').concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId," channels:").concat(i.channels)),this.trackId=e,this.currentTrack=i,this.hls.trigger(ee.AUDIO_TRACK_SWITCHING,fe({},i)),n))){var a=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(a)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||zt(e,i,Xt)))return r}if(e){for(var n=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,c=0;c<t.length;c++){if(zt({name:n,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[c],Xt))return c}for(var d=0;d<t.length;d++){var h=t[d];if(ls(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var v=t[f];if(ls(e.attrs,v.attrs,["LANGUAGE"]))return f}}return-1}},{key:"loadPlaylist",value:function(e){E(t,"loadPlaylist",this,3)([]);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&$t(r.url,this.hls)&&this.scheduleLoading(r,e)}},{key:"loadingPlaylist",value:function(e,r){E(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ee.AUDIO_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}}])}(ss),ds=function(){return o(function e(t){a(this,e),this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t},[{key:"destroy",value:function(){this.tracks=this.queues=null}},{key:"append",value:function(e,t,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(e[0].execute(),e.splice(0,1))})}},{key:"unblockAudio",value:function(e){null!==this.queues&&(this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio"))}},{key:"executeNext",value:function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var n=null==(i=this.tracks[e])?void 0:i.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}}},{key:"shiftAndExecuteNext",value:function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}},{key:"current",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}},{key:"toString",value:function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}},{key:"list",value:function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer".concat(i.updating?" updating":"").concat(r.ended?" ended":"").concat(r.ending?" ending":""):"none"}},{key:"listOps",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e].map(function(e){return e.label}).join(", "))||""}}])}(),hs=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,fs="HlsJsTrackRemovedError",vs=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e])).name=fs,r}return d(t,e),o(t)}(L(Error)),gs=function(e){function t(e,r){var i,s;return a(this,t),(i=n(this,t,["buffer-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.blockedAudioAppend=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(n.removeEventListener("sourceopen",i._onMediaSourceOpen),r.removeEventListener("emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(ee.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){i.log("Media source closed")},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource (".concat(r," > ").concat(t,")"))},i.hls=e,i.fragmentTracker=r,i.appendSource=(s=Te(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}return d(t,e),o(t,[{key:"hasSourceTypes",value:function(){return Object.keys(this.tracks).length>0}},{key:"destroy",value:function(){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}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.BUFFER_RESET,this.onBufferReset,this),e.on(ee.BUFFER_APPENDING,this.onBufferAppending,this),e.on(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ee.BUFFER_EOS,this.onBufferEos,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.FRAG_PARSED,this.onFragParsed,this),e.on(ee.FRAG_CHANGED,this.onFragChanged,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.BUFFER_RESET,this.onBufferReset,this),e.off(ee.BUFFER_APPENDING,this.onBufferAppending,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.BUFFER_EOS,this.onBufferEos,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.FRAG_PARSED,this.onFragParsed,this),e.off(ee.FRAG_CHANGED,this.onFragChanged,this),e.off(ee.ERROR,this.onError,this)}},{key:"transferMedia",value:function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var a=this.isQueued();(n||a)&&this.warn("Transfering MediaSource with".concat(a?" operations in queue":"").concat(n?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}var s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===r?de(i,s.tracks):this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];r&&(i[r]=de({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null}),{media:t,mediaSource:r,tracks:i}}},{key:"initTracks",value:function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}},{key:"onManifestLoading",value:function(){this.bufferCodecEventsTotal=0,this.details=null}},{key:"onManifestParsed",value:function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log("".concat(i," bufferCodec event(s) expected.")),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=Te(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,ps(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}r.addEventListener("emptied",this._onMediaEmptied)}}},{key:"assignMediaSource",value:function(e){var t,r;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(r=e.constructor)?void 0:r.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))}},{key:"attachTransferred",value:function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then(function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()})};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(Kt(i,function(e,t){return"initSegment"===e?void 0:t}),";\ntransfer tracks: ").concat(Kt(n,function(e,t){return"initSegment"===e?void 0:t}),"}")),!Se(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,c=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return c-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(l," -> ").concat(c)):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(n),'"->"').concat(Object.keys(i),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(ee.MEDIA_DETACHING,{}),this.onMediaAttaching(ee.MEDIA_ATTACHING,r),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=jr.getBuffered(a);s.detectEvictedFragments(r,l,o,null,!0)}var u=ms(r),c=[r,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}}},{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"onMediaDetaching",value:function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source ".concat(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(function(e){var t=m(e,1)[0];t&&r.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: ".concat(e.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}a.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("sourceended",this._onMediaSourceEnded),a.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.removeEventListener("startstreaming",this._onStartStreaming),a.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&ps(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(ee.MEDIA_DETACHED,t)}},{key:"onBufferReset",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];r&&e.resetBuffer(r)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset ".concat(e),t)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[ms(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)}},{key:"resetQueue",value:function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new ds(this.tracks)}},{key:"onBufferCodecs",value:function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(a,'" (current SB count ').concat(this.sourceBufferCount,")"));var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some(function(e){return!n[e]});s||o?this.warn('Unsupported transition between "'.concat(Object.keys(n),'" and "').concat(a,'" SourceBuffers')):(a.forEach(function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,c=s.container,d=s.metadata,h=s.supplemental,f=n[e],v=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;f||(f=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:h,container:c,levelCodec:u,metadata:d,id:o});var y=St(p,m),E=null==y?void 0:y.replace(hs,"$1"),k=St(l,u),T=null==(a=k)?void 0:a.replace(hs,"$1");k&&y&&E!==T&&("audio"===e.slice(0,5)&&(k=Tt(k,i.appendSource)),i.log("switching codec ".concat(p," to ").concat(k)),k!==(f.pendingCodec||f.codec)&&(f.pendingCodec=k),f.container=c,i.appendChangeType(e,c,k))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,r){var i=this,n="".concat(t,";codecs=").concat(r),a={label:"change-type=".concat(n),execute:function(){var a=i.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(i.log("changing ".concat(e," sourceBuffer type to ").concat(n)),s.changeType(n),a.codec=r,a.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change ".concat(e," SourceBuffer type"),t)}};this.append(a,e,this.isPending(this.tracks[e]))}},{key:"blockAudio",value:function(e){var t,r=this,i=e.start,n=i+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,ae))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t=r.tracks.video;(r.lastVideoAppendEnd>n||null!=t&&t.buffer&&jr.isBuffered(t.buffer,n)||!0===(null==(e=r.fragmentTracker.getAppendedFrag(n,ae))?void 0:e.gap))&&(r.blockedAudioAppend=null,r.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}}},{key:"unblockAudio",value:function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}},{key:"onBufferAppending",value:function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,c=t.offset,d=u.buffering[a],h=o.sn,f=o.cc,v=self.performance.now();d.start=v;var g=o.stats.buffering,p=l?l.stats.buffering:null;0===g.start&&(g.start=v),p&&0===p.start&&(p.start=v);var y=i.audio,E=!1;"audio"===a&&"audio/mpeg"===(null==y?void 0:y.container)&&(E=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var k=i.video,T=null==k?void 0:k.buffer;if(T&&"initSegment"!==h){var S=l||o,b=this.blockedAudioAppend;if("audio"!==a||"main"===s||this.blockedAudioAppend||k.ending||k.ended){if("video"===a){var A=S.end;if(b){var L=b.frag.start;(A>L||A<this.lastVideoAppendEnd||jr.isBuffered(T,L))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}else{var I=S.start+.05*S.duration,R=T.buffered,w=this.currentOp("video");R.length||w?!w&&!jr.isBuffered(T,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(S):this.blockAudio(S)}}var P=(l||o).start,x={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(E?r.updateTimestampOffset(t,P,.1,a,h,f):void 0!==c&&X(c)&&r.updateTimestampOffset(t,c,1e-6,a,h,f)),r.appendExecutor(n,a)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);var t={};r.sourceBuffers.forEach(function(e){var r=m(e,2),i=r[0],n=r[1];i&&(t[i]=jr.getBuffered(n))}),r.appendErrors[a]=0,"audio"===a||"video"===a?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(ee.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:o.type,timeRanges:t})},onError:function(e){var t,i={type:J.MEDIA_ERROR,parent:o.type,details:Z.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},n=null==(t=r.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=Z.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&r.mediaSourceOpenOrEnded&&!n)i.errorAction=Tr(!0);else if(e.name===fs&&0===r.sourceBufferCount)i.errorAction=Tr(!0);else{var s=++r.appendErrors[a];r.warn("Failed ".concat(s,"/").concat(r.hls.config.appendErrorMaxRetry,' times to append segment in "').concat(a,'" sourceBuffer (').concat(n||"no media error",")")),(s>=r.hls.config.appendErrorMaxRetry||n)&&(i.fatal=!0)}r.hls.trigger(ee.ERROR,i)}};this.log('queuing "'.concat(a,'" append sn: ').concat(h).concat(l?" p: "+l.index:""," of ").concat(o.type===ae?"level":"track"," ").concat(o.level," cc: ").concat(f)),this.append(x,a,this.isPending(this.tracks[a]))}},{key:"getFlushOp",value:function(e,t,r){var i=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(r)),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){i.hls.trigger(ee.BUFFER_FLUSHED,{type:e})},onError:function(n){i.warn("Failed to remove ".concat(t,"-").concat(r,' from "').concat(e,'" SourceBuffer'),n)}}}},{key:"onBufferFlushing",value:function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach(function(e){var t=m(e,1)[0];t&&r.append(r.getFlushOp(t,n,a),t)})}},{key:"onFragParsed",value:function(e,t){var r=this,i=t.frag,n=t.part,a=[],s=n?n.elementaryStreams:i.elementaryStreams;s[_e]?a.push("audiovideo"):(s[De]&&a.push("audio"),s[Ce]&&a.push("video"));0===a.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(i.type," level: ").concat(i.level," sn: ").concat(i.sn)),this.blockBuffers(function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.hls.trigger(ee.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type})},a).catch(function(e){r.warn("Fragment buffered callback ".concat(e)),r.stepOperationQueue(r.sourceBufferTypes)})}},{key:"onFragChanged",value:function(e,t){this.trimBuffers()}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some(function(t){var r=m(t,1)[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var r,i=this;this.sourceBuffers.forEach(function(e){var r=m(e,1)[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log("".concat(r," buffer reached EOS"))))}});var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,r=m(e,1)[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(function(){i.tracksEnded();var e=i.mediaSource;e&&"open"===e.readyState?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(ee.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(e.readyState))})):(this.tracksEnded(),this.hls.trigger(ee.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}},{key:"tracksEnded",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())}},{key:"updateDuration",value:function(){var e=this;this.blockUntilOpen(function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)})}},{key:"onError",value:function(e,t){if(t.details===Z.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;X(i)&&i!==t.frag.level&&this.resetAppendErrors()}}},{key:"resetAppendErrors",value:function(){this.appendErrors={audio:0,video:0,audiovideo:0}}},{key:"trimBuffers",value:function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.sourceBufferCount){var i=e.config,n=r.currentTime,a=t.levelTargetDuration,s=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(X(s)&&s>=0){var o=Math.max(s,a),l=Math.floor(n/a)*a-o;this.flushBackBuffer(n,a,l)}var u=i.frontBufferFlushThreshold;if(X(u)&&u>0){var c=Math.max(i.maxBufferLength,u),d=Math.max(c,a),h=Math.floor(n/a)*a+d;this.flushFrontBuffer(n,a,h)}}}},{key:"flushBackBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(e){var t=m(e,2),n=t[0],a=t[1];if(a){var s=jr.getBuffered(a);if(s.length>0&&r>s.start(0)){var o;i.hls.trigger(ee.BACK_BUFFER_REACHED,{bufferEnd:r});var l=i.tracks[n];if(null!=(o=i.details)&&o.live)i.hls.trigger(ee.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=l&&l.ended)return void i.log("Cannot flush ".concat(n," back buffer while SourceBuffer is in ended state"));i.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}},{key:"flushFrontBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(t){var n=m(t,2),a=n[0],s=n[1];if(s){var o=jr.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(r>u||e>=u&&e<=c)return;i.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return X(a)?{duration:a}:null;var s=this.media.duration;return i>(X(r.duration)?r.duration:0)&&i>s||!X(s)?{duration:i}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==t&&(X(t)&&this.log("Updating MediaSource duration to ".concat(t.toFixed(3))),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to ".concat(n.duration,". Setting seekable range to ").concat(r,"-").concat(i,".")),n.setLiveSeekableRange(r,i)))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"checkPendingTracks",value:function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(Kt(r))),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}},{key:"bufferCreated",value:function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach(function(r){var i=m(r,2),n=i[0],a=i[1];if(n){var s=e.tracks[n];t[n]={buffer:a,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(ee.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];e.executeNext(r)})}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o="".concat(a.container,";codecs=").concat(s);a.codec=s,this.log("creating sourceBuffer(".concat(o,")").concat(this.currentOp(n)?" Queued":""," ").concat(Kt(a)));try{var l=r.addSourceBuffer(o),u=ms(n),c=[n,l];t[u]=c,a.buffer=l}catch(e){var d;return this.error("error while trying to add sourceBuffer: ".concat(e.message)),this.shiftAndExecuteNext(n),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[n],void this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}},{key:"getTrackCodec",value:function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&vt(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n<i.length;n++)ft(i[n],"video")||r.push(i[n]);return t&&r.push(t),r.join(",")}(i,r));var n=St(i,e.levelCodec);return n?"audio"===t.slice(0,5)?Tt(n,this.appendSource):n:""}},{key:"trackSourceBuffer",value:function(e,t){var r=this,i=t.buffer;if(i){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,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",function(e,t){var i=t.removedRanges;null!=i&&i.length&&r.hls.trigger(ee.BUFFER_FLUSHED,{type:e})})}}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"onSBUpdateStart",value:function(e){var t=this.currentOp(e);t&&t.onStart()}},{key:"onSBUpdateEnd",value:function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var r,i=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(null==(r=this.mediaSource)?void 0:r.readyState));this.error("".concat(i),t),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var n=this.currentOp(e);n&&n.onError(i)}},{key:"updateTimestampOffset",value:function(e,t,r,i,n,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating ".concat(i," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(n," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)return this.warn("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist")),void this.shiftAndExecuteNext(e);var o=X(i.duration)?i.duration:1/0,l=X(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(r,o,l);c>u&&(!a.ending||a.ended)?(a.ended=!1,this.log("Removing [".concat(u,",").concat(c,"] from the ").concat(e," SourceBuffer")),s.remove(u,c)):this.shiftAndExecuteNext(e)}},{key:"appendExecutor",value:function(e,t){var r=this.tracks[t],i=null==r?void 0:r.buffer;if(!i)throw new vs("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));r.ending=!1,r.ended=!1,i.appendBuffer(e)}},{key:"blockUntilOpen",value:function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(function(e){t.warn("SourceBuffer blocked callback ".concat(e)),t.stepOperationQueue(t.sourceBufferTypes)});else try{e()}catch(e){this.warn("Callback run without blocking ".concat(this.operationQueue," ").concat(e))}}},{key:"isUpdating",value:function(){return this.sourceBuffers.some(function(e){var t=m(e,2),r=t[0],i=t[1];return r&&i.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var r=m(t,1)[0];return r&&!!e.currentOp(r)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"blockBuffers",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=r.map(function(e){return t.appendBlocker(e)});return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(function(r){i===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;i&&!i.updating&&t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}},{key:"appendBlocker",value:function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}},{key:"currentOp",value:function(e){return this.operationQueue?this.operationQueue.current(e):null}},{key:"executeNext",value:function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}},{key:"shiftAndExecuteNext",value:function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){return t+(e.isPending(e.tracks[r])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(m(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return m(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach(function(e){r.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}}])}(ve);function ps(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function ms(e){return"audio"===e?1:0}var ys=function(){function e(t){a(this,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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}return o(e,[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"destroy",value:function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListener",value:function(){var e=this.hls;e.off(ee.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"onFpsDropLevelCapping",value:function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}},{key:"onManifestParsed",value:function(e,t){var r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}},{key:"onLevelsUpdated",value:function(e,t){this.timer&&X(this.autoLevelCapping)&&this.detectPlayerSize()}},{key:"onBufferCodecs",value:function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}},{key:"onMediaDetaching",value:function(){this.stopCapping(),this.media=null}},{key:"detectPlayerSize",value:function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(r,": ").concat(e[r].height,"p@").concat(e[r].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter(function(e,i){return r.isLevelAllowed(e)&&i<=t});return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}},{key:"startCapping",value:function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}},{key:"stopCapping",value:function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}},{key:"getDimensions",value:function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}},{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}},{key:"isLevelAllowed",value:function(e){return!this.restrictedLevels.some(function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height})}}],[{key:"getMaxLevelByMediaSize",value:function(e,t,r){if(null==e||!e.length)return-1;for(var i=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=Math.max(t,r),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&i(o,e[s+1])){n=s;break}}return n}}])}(),Es={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ks={HLS:"h"},Ts=o(function e(t,r){a(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=r});function Ss(e,t,r,i){return new Error("failed to ".concat(e,' "').concat((n=t,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"===S(n)?JSON.stringify(n):String(n)),'" as ').concat(r),{cause:i});var n}function bs(e,t,r){return Ss("serialize",e,t,r)}var As=o(function e(t){a(this,e),this.description=t}),Ls="Bare Item";function Is(e){if(!1===ArrayBuffer.isView(e))throw bs(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,k(t)))),":");var t}function Rs(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw bs(e,"Integer");return e.toString()}function ws(e,t){if(e<0)return-ws(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var i=Math.floor(e*r);return(i%2==0?i:i+1)/r}return Math.round(e*r)/r}function Ps(e){var t=ws(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw bs(e,"Decimal");var r=t.toString();return r.includes(".")?r:"".concat(r,".0")}var xs=/[\x00-\x1f\x7f]+/;function Ds(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw bs(r,"Token");return r}function Cs(e){switch(S(e)){case"number":if(!X(e))throw bs(e,Ls);return Number.isInteger(e)?Rs(e):Ps(e);case"string":return function(e){if(xs.test(e))throw bs(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return Ds(e);case"boolean":return function(e){if("boolean"!=typeof e)throw bs(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@".concat(Rs(e.getTime()/1e3))}(e);if(e instanceof Uint8Array)return Is(e);if(e instanceof As)return Ds(e);default:throw bs(e,Ls)}}function _s(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw bs(e,"Key");return e}function Ms(e){return null==e?"":Object.entries(e).map(function(e){var t=m(e,2),r=t[0],i=t[1];return!0===i?";".concat(_s(r)):";".concat(_s(r),"=").concat(Cs(i))}).join("")}function Os(e){return e instanceof Ts?"".concat(Cs(e.value)).concat(Ms(e.params)):Cs(e)}function Fs(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==S(e)||null==e)throw bs(e,"Dict");var r=e instanceof Map?e.entries():Object.entries(e),i=(null==t?void 0:t.whitespace)?" ":"";return Array.from(r).map(function(e){var t=m(e,2),r=t[0],i=t[1];i instanceof Ts==!1&&(i=new Ts(i));var n,a=_s(r);return!0===i.value?a+=Ms(i.params):(a+="=",Array.isArray(i.value)?a+="(".concat((n=i).value.map(Os).join(" "),")").concat(Ms(n.params)):a+=Os(i)),a}).join(",".concat(i))}function Ns(e,t){return Fs(e,t)}var Us="CMCD-Object",Bs="CMCD-Request",Gs="CMCD-Session",Hs="CMCD-Status",Vs={br:Us,ab:Us,d:Us,ot:Us,tb:Us,tpb:Us,lb:Us,tab:Us,lab:Us,url:Us,pb:Bs,bl:Bs,tbl:Bs,dl:Bs,ltc:Bs,mtp:Bs,nor:Bs,nrr:Bs,rc:Bs,sn:Bs,sta:Bs,su:Bs,ttfb:Bs,ttfbb:Bs,ttlb:Bs,cmsdd:Bs,cmsds:Bs,smrt:Bs,df:Bs,cs:Bs,ts:Bs,cid:Gs,pr:Gs,sf:Gs,sid:Gs,st:Gs,v:Gs,msd:Gs,bs:Hs,bsd:Hs,cdn:Hs,rtp:Hs,bg:Hs,pt:Hs,ec:Hs,e:Hs},Ks=Bs;function js(e,t){var r={};if(!e)return r;var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce(function(e,t){var r;return null===(r=i[t])||void 0===r||r.forEach(function(r){return e[r]=t}),e},{})):{};return n.reduce(function(t,r){var i,n=Vs[r]||a[r]||Ks;return(null!==(i=t[n])&&void 0!==i?i:t[n]={})[r]=e[r],t},r)}var Ys="event";var Ws=function(e){return Math.round(e)},qs=function(e,t){return Array.isArray(e)?e.map(function(e){return qs(e,t)}):e instanceof Ts&&"string"==typeof e.value?new Ts(qs(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1);n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+r.search+r.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},zs=function(e){return 100*Ws(e/100)},Xs={br:Ws,d:Ws,bl:zs,dl:zs,mtp:zs,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof Ts&&"string"==typeof e.value?r=new Ts([e]):"string"==typeof e&&(r=[e])),qs(r,t)},rtp:zs,tb:Ws},Qs="request",$s="response",Js=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Zs=["e"],eo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function to(e){return eo.test(e)}var ro=["d","dl","nor","ot","rtp","su"];var io=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];var no=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ao(e){return no.includes(e)||to(e)}var so=l(l(l({},$s,function(e){return Js.includes(e)||ro.includes(e)||io.includes(e)||to(e)}),Ys,function(e){return Js.includes(e)||Zs.includes(e)||to(e)}),Qs,function(e){return Js.includes(e)||ro.includes(e)||to(e)});function oo(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(null==e||"object"!==S(e))return r;var i=t.version||e.v||1,n=t.reportingMode||Qs,a=1===i?ao:so[n],s=Object.keys(e).filter(a),o=t.filter;"function"==typeof o&&(s=s.filter(o));var l=n===$s||n===Ys;l&&!s.includes("ts")&&s.push("ts"),i>1&&!s.includes("v")&&s.push("v");var u=de({},Xs,t.formatters),c={version:i,reportingMode:n,baseUrl:t.baseUrl};return s.sort().forEach(function(t){var n=e[t],a=u[t];if("function"==typeof a&&(n=a(n,c)),"v"===t){if(1===i)return;n=i}"pr"==t&&1===n||(l&&"ts"===t&&!X(n)&&(n=Date.now()),function(e){return"number"==typeof e?X(e):null!=e&&""!==e&&!1!==e}(n)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof n&&(n=new As(n)),r[t]=n))}),r}function lo(e,t,r){return de(e,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(!e)return r;var i=js(oo(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(i).reduce(function(e,t){var r=m(t,2),i=r[0],n=Ns(r[1],{whitespace:!1});return n&&(e[i]=n),e},r)}(t,r))}function uo(e){if(!e)return"";var t=function(e){return e?Ns(oo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),{whitespace:!1}):""}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return encodeURIComponent(t)}var co=/CMCD=[^&#]+/;function ho(e,t,r){var i=function(e){if(!e)return"";var t=uo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return"".concat("CMCD","=").concat(t)}(t,r);if(!i)return e;if(co.test(e))return e.replace(co,i);var n=e.includes("?")?"&":"?";return"".concat(e).concat(n).concat(i)}var fo=function(){return o(function e(t){var r=this;a(this,e),this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0),r.buffering=!0},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1},this.applyPlaylistData=function(e){try{r.apply(e,{ot:Es.MANIFEST,su:!r.initialized})}catch(e){r.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var t=e.frag,i=e.part,n=r.hls.levels[t.level],a=r.getObjectType(t),s={d:1e3*(i||t).duration,ot:a};a!==Es.VIDEO&&a!==Es.AUDIO&&a!=Es.MUXED||(s.br=n.bitrate/1e3,s.tb=r.getTopBandwidth(a)/1e3,s.bl=r.getBufferLength(a));var o=i?r.getNextPart(i):r.getNextFrag(t);null!=o&&o.url&&o.url!==t.url&&(s.nor=o.url),r.apply(e,s)}catch(e){r.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=t;var i=this.config=t.config,n=i.cmcd;null!=n&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.sessionId,this.cid=n.contentId,this.useHeaders=!0===n.useHeaders,this.includeKeys=n.includeKeys,this.registerListeners())},[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}},{key:"onMediaDetached",value:function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}},{key:"onBufferCreated",value:function(e,t){var r,i;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer}},{key:"createData",value:function(){var e;return{v:1,sf:ks.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}},{key:"apply",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};de(t,this.createData());var r=t.ot===Es.INIT||t.ot===Es.VIDEO||t.ot===Es.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var i=this.includeKeys;i&&(t=Object.keys(t).reduce(function(e,r){return i.includes(r)&&(e[r]=t[r]),e},{}));var n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),lo(e.headers,t,n)):e.url=ho(e.url,t,n)}},{key:"getNextFrag",value:function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}}},{key:"getNextPart",value:function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}}},{key:"getObjectType",value:function(e){var t=e.type;return"subtitle"===t?Es.TIMED_TEXT:"initSegment"===e.sn?Es.INIT:"audio"===t?Es.AUDIO:"main"===t?this.hls.audioTracks.length?Es.VIDEO:Es.MUXED:void 0}},{key:"getTopBandwidth",value:function(e){var t,r=0,i=this.hls;if(e===Es.AUDIO)t=i.audioTracks;else{var n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;t=i.levels.slice(0,a)}return t.forEach(function(e){e.bitrate>r&&(r=e.bitrate)}),r>0?r:NaN}},{key:"getBufferLength",value:function(e){var t=this.media,r=e===Es.AUDIO?this.audioBuffer:this.videoBuffer;return r&&t?1e3*jr.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len:NaN}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,r=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}}])}(),vo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["content-steering",e.logger])).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=e,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.ERROR,this.onError,this))}},{key:"pathways",value:function(){return(this.levels||[]).reduce(function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e},[])}},{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}},{key:"startLoad",value:function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}},{key:"stopLoad",value:function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}},{key:"clearTimeout",value:function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"removeLevel",value:function(e){var t=this.levels;t&&(this.levels=t.filter(function(t){return t!==e}))}},{key:"onManifestLoading",value:function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}},{key:"onManifestParsed",value:function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}},{key:"onError",value:function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===fr&&r.flags===mr){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a),t.details!==Z.BUFFER_APPEND_ERROR||t.fatal?r.resolved||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(i?i.length:i," priorities: ").concat(Kt(n)," penalized: ").concat(Kt(this.penalizedPathways))):r.resolved=!0}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(r,'"')),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}},{key:"getLevelsForPathway",value:function(e){return null===this.levels?[]:this.levels.filter(function(t){return e===t.pathwayId})}},{key:"updatePathwayPriority",value:function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(function(e){i-r[e]>3e5&&delete r[e]});for(var n=0;n<e.length;n++){var a=e[n];if(!(a in r)){if(a===this.pathwayId)return;var s=this.hls.nextLoadLevel,o=this.hls.levels[s];if((t=this.getLevelsForPathway(a)).length>0){this.log('Setting Pathway to "'.concat(a,'"')),this.pathwayId=a,Zi(t),this.hls.trigger(ee.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(o.bitrate," to ").concat(l.bitrate)),this.hls.nextLoadLevel=s);break}}}}},{key:"getPathwayForGroupId",value:function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n<i.length;n++)if(t===ie&&i[n].hasAudioGroup(e)||t===ne&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return r}},{key:"clonePathways",value:function(e){var t=this,r=this.levels;if(r){var i={},n={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new Jr(e.attrs);t["PATHWAY-ID"]=a;var r=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);r&&(i[t.AUDIO]=r,t.AUDIO=r),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=po(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new Gt({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(var c=1;c<e.audioGroups.length;c++)u.addGroupId("audio","".concat(e.audioGroups[c],"_clone_").concat(a));if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)u.addGroupId("text","".concat(e.subtitleGroups[d],"_clone_").concat(a));return u});r.push.apply(r,k(l)),go(t.audioTracks,i,o,a),go(t.subtitleTracks,n,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,r=this,i=this.hls.config,n=i.loader;this.loader&&this.loader.destroy(),this.loader=new n(i);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: ".concat(e))}if("data:"!==t.protocol){var a=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+a)}var s={responseType:"json",url:t.href},o=i.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:function(e,i,n,a){r.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}r.scheduleRefresh(r.uri||n.url),l&&r.clonePathways(l);var c={steeringManifest:s,url:t.toString()};r.hls.trigger(ee.STEERING_MANIFEST_LOADED,c),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,i,n){if(r.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest (".concat(t.url,")")),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var r,i=null==(r=t.hls)?void 0:r.media;!i||i.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},r)}}])}(ve);function go(e,t,r,i){e&&Object.keys(t).forEach(function(n){var a=e.filter(function(e){return e.groupId===n}).map(function(e){var a=de({},e);return a.details=void 0,a.attrs=new Jr(a.attrs),a.url=a.attrs.URI=po(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=i,a});e.push.apply(e,k(a))})}function po(e,t,r,i){var n,a=i.HOST,s=i.PARAMS,o=i[r];t&&(n=null==o?void 0:o[t])&&(e=n);var l=new self.URL(e);return a&&!n&&(l.host=a),s&&Object.keys(s).sort().forEach(function(e){e&&l.searchParams.set(e,s[e])}),l.href}var mo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["eme",e.logger])).hls=void 0,r.config=void 0,r.media=null,r.mediaResolved=void 0,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.bannedKeyIds={},r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,n='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(r.debug(n),null!==i){if(!r.keyFormatPromise){var a=Object.keys(r.keySystemAccessPromises);a.length||(a=Ei(r.config));var s=a.map(yi).filter(function(e){return!!e});r.keyFormatPromise=r.getKeyFormatPromise(s)}r.keyFormatPromise.then(function(a){var s=mi(a);if("sinf"===t&&s===hi.FAIRPLAY){var o;try{var l=Ve(new Uint8Array(i)),u=rt(oi(JSON.parse(l).sinf));if(!u)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(u.subarray(8,24))}catch(e){return void r.warn("".concat(n," Failed to parse sinf: ").concat(e))}for(var c,d=Ae(o),h=r,f=h.keyIdToKeySessionPromise,v=h.mediaKeySessions,g=f[d],p=function(){var e=v[m],n=e.decryptdata;if(!n.keyId)return 0;var a=Ae(n.keyId);return ii(o,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(d)?(g=f[a])?(n.pssh||(delete f[a],n.pssh=new Uint8Array(i),n.keyId=o,(g=f[d]=g.then(function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")})).catch(function(e){return r.handleError(e)})),1):0:void 0},m=0;m<v.length&&(0===(c=p())||1!==c);m++);g||r.handleError(new Error("Key ID ".concat(d," not encountered in playlist. Key-system sessions ").concat(v.length,".")))}else r.log('Ignoring "'.concat(e.type,'" event with init data type: "').concat(t,'" for selected key-system ').concat(s))}).catch(function(e){return r.handleError(e)})}},r.onWaitingForKey=function(e){r.log('"'.concat(e.type,'" event'))},r.hls=e,r.config=e.config,r.registerListeners(),r}return d(t,e),o(t,[{key:"destroy",value:function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}},{key:"registerListeners",value:function(){this.hls.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(ee.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(ee.DESTROYING,this.onDestroying,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(ee.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(ee.DESTROYING,this.onDestroying,this)}},{key:"getLicenseServerUrl",value:function(e){var t=this.config,r=t.drmSystems,i=t.widevineLicenseUrl,n=null==r?void 0:r[e];return n?n.licenseUrl:e===hi.WIDEVINE&&i?i:void 0}},{key:"getLicenseServerUrlOrThrow",value:function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'.concat(e,'"'));return t}},{key:"getServerCertificateUrl",value:function(e){var t=this.config.drmSystems,r=null==t?void 0:t[e];if(r)return r.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]'))}},{key:"attemptKeySystemAccess",value:function(e){var t=this,r=this.hls.levels,i=function(e,t,r){return!!e&&r.indexOf(e)===t},n=r.map(function(e){return e.audioCodec}).filter(i),a=r.map(function(e){return e.videoCodec}).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(r,i){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then(function(e){return r({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):i(t instanceof ko?t:new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}},{key:"requestMediaKeySystemAccess",value:function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function ".concat(r);return null===Ti&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(i))}return r(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,r){var i,n=this,a=function(e,t,r,i){var n;switch(e){case hi.FAIRPLAY:n=["cenc","sinf"];break;case hi.WIDEVINE:case hi.PLAYREADY:n=["cenc"];break;case hi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}}),videoCapabilities:r.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}})}]}(n,t,r,i)}(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(i=s)?void 0:i.keySystemAccess;if(!o){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(Kt(a))),o=this.requestMediaKeySystemAccess(e,a);var l=s=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(function(t){n.log('Failed to obtain access to key-system "'.concat(e,'": ').concat(t))}),o.then(function(t){n.log('Access for key-system "'.concat(t.keySystem,'" obtained'));var r=n.fetchServerCertificate(e);n.log('Create media-keys for "'.concat(e,'"'));var i=l.mediaKeys=t.createMediaKeys().then(function(t){return n.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,r.then(function(r){return r?n.setMediaKeysServerCertificate(t,e,r):t})});return i.catch(function(t){n.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),i})}return o.then(function(){return s.mediaKeys})}},{key:"createMediaKeySessionContext",value:function(e){var t=e.decryptdata,r=e.keySystem,i=e.mediaKeys;this.log('Creating key-system session "'.concat(r,'" keyId: ').concat(Ae(t.keyId||[])," keyUri: ").concat(t.uri));var n=i.createSession(),a={decryptdata:t,keySystem:r,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}},{key:"renewKeySession",value:function(e){var t=e.decryptdata;if(t.pssh){var r=this.createMediaKeySessionContext(e),i=yo(t);this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}},{key:"updateKeySession",value:function(e,t){var r=e.mediaKeysSession;return this.log('Updating key-session "'.concat(r.sessionId,'" for keyId ').concat(Ae(e.decryptdata.keyId||[]),"\n } (data length: ").concat(t.byteLength,")")),r.update(t)}},{key:"getSelectedKeySystemFormats",value:function(){var e=this;return Object.keys(this.keySystemAccessPromises).map(function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}}).filter(function(e){return!!e.hasMediaKeys}).map(function(e){return yi(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var r=e.keySystem,i=e.mediaKeys;return t.attemptSetMediaKeys(r,i)})}},{key:"selectKeySystem",value:function(e){var t=this;return new Promise(function(r,i){t.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,n=yi(t);n?r(n):i(new Error('Unable to find format for key-system "'.concat(t,'"')))}).catch(i)})}},{key:"selectKeySystemFormat",value:function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(e.sn," ").concat(e.type,": ").concat(e.level,") key formats ").concat(t.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}},{key:"getKeyFormatPromise",value:function(e){var t=Ei(this.config),r=e.map(mi).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(r)}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var i=Eo(e,t[r]);if(i)return i}}},{key:"loadKey",value:function(e){var t=this,r=e.keyInfo.decryptdata,i=yo(r),n=this.bannedKeyIds[i];if(n||"internal-error"===this.getKeyStatus(r)){var a=To(n||"internal-error",r);return this.handleError(a,e.frag),Promise.reject(a)}var s="(keyId: ".concat(i,' format: "').concat(r.keyFormat,'" method: ').concat(r.method," uri: ").concat(r.uri,")");this.log("Starting session for key ".concat(s));var o=this.keyIdToKeySessionPromise[i];if(!o){var l=this.getKeySystemForKeyPromise(r).then(function(i){var n=i.keySystem,a=i.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: ".concat(e.frag.sn," ").concat(e.frag.type,": ").concat(e.frag.level," using key ").concat(s)),t.attemptSetMediaKeys(n,a).then(function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:n,mediaKeys:a,decryptdata:r})})}).then(function(e){var i=r.pssh?r.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return l.catch(function(r){return t.handleError(r,e.frag)}),this.keyIdToKeySessionPromise[i]=l,l}return o.catch(function(i){if(i instanceof ko){var n=fe({},i.data);"internal-error"===t.getKeyStatus(r)&&(n.decryptdata=r);var a=new ko(n,i.message);t.handleError(a,e.frag)}}),o}},{key:"throwIfDestroyed",value:function(){if(!this.hls)throw new Error("invalid state")}},{key:"handleError",value:function(e,t){if(this.hls)if(e instanceof ko){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error("".concat(e.message).concat(r?" (".concat(Ae(r.keyId||[]),")"):"")),this.hls.trigger(ee.ERROR,e.data)}else this.error(e.message),this.hls.trigger(ee.ERROR,{type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}},{key:"getKeySystemForKeyPromise",value:function(e){var t=yo(e),r=this.keyIdToKeySessionPromise[t];if(!r){var i=mi(e.keyFormat),n=i?[i]:Ei(this.config);return this.attemptKeySystemAccess(n)}return r}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=Ei(this.config)),0===e.length)throw new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(Kt({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}},{key:"attemptSetMediaKeys",value:function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var n=Promise.all(i).then(function(){return r.media?r.media.setMediaKeys(t):new Promise(function(e,i){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return i(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(i)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(function(){r.log('Media-keys set for "'.concat(e,'"')),i.push(n),r.setMediaKeysQueue=r.setMediaKeysQueue.filter(function(e){return-1===i.indexOf(e)})})}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,r,i){var n,a=this,s=null==(n=this.config.drmSystems)||null==(n=n[e.keySystem])?void 0:n.generateRequest;if(s)try{var o=s.call(this.hls,t,r,e);if(!o)throw new Error("Invalid response from configured generateRequest filter");t=o.initDataType,r=o.initData?o.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===r)return this.log('Skipping key-session request for "'.concat(i,'" (no initData)')),Promise.resolve(e);var l=yo(e.decryptdata),u=e.decryptdata.uri;this.log('Generating key-session request for "'.concat(i,'" keyId: ').concat(l," URI: ").concat(u," (init data type: ").concat(t," length: ").concat(r.byteLength,")"));var c=new Pn,d=e._onmessage=function(t){var r=e.mediaKeysSession;if(r){var i=t.messageType,n=t.message;a.log('"'.concat(i,'" message event for session "').concat(r.sessionId,'" message size: ').concat(n.byteLength)),"license-request"===i||"license-renewal"===i?a.renewLicense(e,n).catch(function(e){c.eventNames().length?c.emit("error",e):a.handleError(e)}):"license-release"===i?e.keySystem===hi.FAIRPLAY&&a.updateKeySession(e,li("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(i,'"'))}else c.emit("error",new Error("invalid state"))},h=function(e,t){var r;t.keyStatus=e,e.startsWith("usable")?c.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=To(e,t.decryptdata):"expired"===e?r=new Error("key expired (keyId: ".concat(l,")")):"released"===e?r=new Error("key released"):"status-pending"===e||a.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(l,")")),r&&(c.eventNames().length?c.emit("error",r):a.handleError(r))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){var r=a.getKeyStatuses(e);if(Object.keys(r).some(function(e){return"status-pending"!==r[e]})){if("expired"===r[l])return a.log("Expired key ".concat(Kt(r),' in key-session "').concat(e.mediaKeysSession.sessionId,'"')),void a.renewKeySession(e);var i=r[l];if(i)h(i,e);else{var n;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(n=e.keyStatusTimeouts)[l]||(n[l]=self.setTimeout(function(){if(e.mediaKeysSession&&a.mediaKeys){var t=a.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return a.log("No status for keyId ".concat(l,' in key-session "').concat(e.mediaKeysSession.sessionId,'". Using session key-status ').concat(t," from other session.")),h(t,e);a.log("key status for ".concat(l,' in key-session "').concat(e.mediaKeysSession.sessionId,'" timed out after ').concat(1e3,"ms")),h(i="internal-error",e)}},1e3)),a.log("No status for keyId ".concat(l," (").concat(Kt(r),")."))}}}else c.emit("error",new Error("invalid state"))};ln(e.mediaKeysSession,"message",d),ln(e.mediaKeysSession,"keystatuseschange",f);var v=new Promise(function(e,t){c.on("error",t),c.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,r).then(function(){a.log('Request generated for key-session "'.concat(e.mediaKeysSession.sessionId,'" keyId: ').concat(l," URI: ").concat(u))}).catch(function(t){throw new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},"Error generating key-session request: ".concat(t))}).then(function(){return v}).catch(function(t){return c.removeAllListeners(),a.removeSession(e).then(function(){throw t})}).then(function(){return c.removeAllListeners(),e})}},{key:"getKeyStatuses",value:function(e){var t=this,r={};return e.mediaKeysSession.keyStatuses.forEach(function(i,n){if("string"==typeof n&&"object"===S(i)){var a=n;n=i,i=a}var s="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);e.keySystem===hi.PLAYREADY&&16===s.length&&ui(s);var o=Ae(s);"internal-error"===i&&(t.bannedKeyIds[o]=i),t.log('key status change "'.concat(i,'" for keyStatuses keyId: ').concat(o,' key-session "').concat(e.mediaKeysSession.sessionId,'"')),r[o]=i}),r}},{key:"fetchServerCertificate",value:function(e){var t=this.config,r=new(0,t.loader)(t),i=this.getServerCertificateUrl(e);return i?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(n,a){var s={responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,i){n(e.data)},onError:function(t,r,n,o){a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:fe({url:s.url,data:void 0},t)},'"'.concat(e,'" certificate request failed (').concat(i,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,r,n){a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:s.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(i,")")))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)})):Promise.resolve()}},{key:"setMediaKeysServerCertificate",value:function(e,t,r){var i=this;return new Promise(function(n,a){e.setServerCertificate(r).then(function(a){i.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(r.byteLength,') on "').concat(t,'"')),n(e)}).catch(function(e){a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}},{key:"renewLicense",value:function(e,t){var r=this;return this.requestLicense(e,new Uint8Array(t)).then(function(t){return r.updateKeySession(e,new Uint8Array(t)).catch(function(t){throw new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)})})}},{key:"unpackPlayReadyKeyMessage",value:function(e,t){var r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var i=(new DOMParser).parseFromString(r,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0)for(var a,s=0,o=n.length;s<o;s++){var l,u,c=null==(l=(a=n[s]).querySelector("name"))?void 0:l.textContent,d=null==(u=a.querySelector("value"))?void 0:u.textContent;c&&d&&e.setRequestHeader(c,d)}var h=i.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return li(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,r,i){var n=this,a=this.config.licenseXhrSetup;return a?Promise.resolve().then(function(){if(!r.decryptdata)throw new Error("Key removed");return a.call(n.hls,e,t,r,i)}).catch(function(s){if(!r.decryptdata)throw s;return e.open("POST",t,!0),a.call(n.hls,e,t,r,i)}).then(function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||i}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}},{key:"requestLicense",value:function(e,t){var r=this,i=this.config.keyLoadPolicy.default;return new Promise(function(n,a){var s=r.getLicenseServerUrlOrThrow(e.keySystem);r.log("Sending license request to URL: ".concat(s));var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!r.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===o.readyState)if(200===o.status){r._requestLicenseFailureCount=0;var l=o.response;r.log("License received ".concat(l instanceof ArrayBuffer?l.byteLength:l));var u=r.config.licenseResponseCallback;if(u)try{l=u.call(r.hls,o,s,e)}catch(e){r.error(e)}n(l)}else{var c=i.errorRetry,d=c?c.maxNumRetry:0;if(r._requestLicenseFailureCount++,r._requestLicenseFailureCount>d||o.status>=400&&o.status<500)a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:s,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed (".concat(s,"). Status: ").concat(o.status," (").concat(o.statusText,")")));else{var h=d-r._requestLicenseFailureCount+1;r.warn("Retrying license request, ".concat(h," attempts left")),r.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,r.setupLicenseXHR(o,s,e,t).then(function(t){var i=t.xhr,n=t.licenseChallenge;e.keySystem==hi.PLAYREADY&&(n=r.unpackPlayReadyKeyMessage(i,n)),i.send(n)}).catch(a)})}},{key:"onDestroying",value:function(){this.unregisterListeners(),this._clear()}},{key:"onMediaAttached",value:function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,ln(r,"encrypted",this.onMediaEncrypted),ln(r,"waitingforkey",this.onWaitingForKey);var i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(un(e,"encrypted",this.onMediaEncrypted),un(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}},{key:"_clear",value:function(){var e,r=this;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};var i=this.mediaResolved;if(i&&i(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ai.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return r.removeSession(e)}).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch(function(e){r.log("Could not clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: ".concat(e))})}))||Promise.resolve())).catch(function(e){r.log("Could not close sessions and clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(e))})}).then(function(){s&&r.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear()}},{key:"onManifestLoaded",value:function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(i.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(i)}}},{key:"removeSession",value:function(e){var t=this,r=e.mediaKeysSession,i=e.licenseXhr,n=e.decryptdata;if(r){this.log('Remove licenses and keys and close session "'.concat(r.sessionId,'" keyId: ').concat(Ae((null==n?void 0:n.keyId)||[]))),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);var s=e.keyStatusTimeouts;s&&Object.keys(s).forEach(function(e){return self.clearTimeout(s[e])});var o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise(function(e,t){self.setTimeout(function(){return t(new Error("MediaKeySession.remove() timeout"))},8e3),r.remove().then(e).catch(t)}):Promise.resolve();return o.catch(function(e){t.log("Could not remove session: ".concat(e)),t.hls&&t.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(e))})}).then(function(){return r.close()}).catch(function(e){t.log("Could not close session: ".concat(e)),t.hls&&t.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(e))})})}return Promise.resolve()}}])}(ve);function yo(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Ae(e.keyId)}function Eo(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}mo.CDMCleanupPromise=void 0;var ko=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r])).data=void 0,e.error||(e.error=new Error(r)),i.data=e,e.err=e.error,i}return d(t,e),o(t)}(L(Error));function To(e,t){var r="output-restricted"===e,i=r?Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ko({type:J.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'.concat(e,'"'))}var So=function(){return o(function e(t){a(this,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=t,this.registerListeners()},[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"registerListeners",value:function(){this.hls.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"destroy",value:function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(ee.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(ee.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}])}();function bo(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Ao(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: ".concat(t))}catch(r){ke.debug("[texttrack-utils]: ".concat(r));try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){ke.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(e))}}"disabled"===r&&(e.mode=r)}function Lo(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(var i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===r&&(e.mode=r)}function Io(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;var i,n=0,a=r;for(;n<=a;)if(t<e[i=Math.floor((a+n)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}return e[n].startTime-t<t-e[a].startTime?n:a}(e,t);if(n>-1)for(var a=n,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;s<a.length;s++)i&&!i(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}function Ro(e){for(var t=[],r=0;r<e.length;r++){var i=e[r];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||t.push(e[r])}return t}var wo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e,"subtitle-track-controller"])).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){for(var e=null,t=Ro(r.media.textTracks),i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}var n=r.findTrackForTextTrack(e);r.subtitleTrack!==n&&r.setSubtitleTrack(n)}},r.registerListeners(),r}return d(t,e),o(t,[{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,E(t,"destroy",this,3)([])}},{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}},{key:"pollTrackChange",value:function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}},{key:"onMediaDetaching",value:function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!i)Ro(r.textTracks).forEach(function(e){Lo(e)})}}},{key:"onManifestLoading",value:function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.subtitleTracks}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.subtitleGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.subtitlePreference;if(!n&&s){this.selectDefaultTrack=!1;var o=qt(s,a);if(o>-1)n=a[o];else{var l=qt(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={subtitleTracks:a};this.log("Updating subtitle tracks, ".concat(a.length,' track(s) found in "').concat(null==r?void 0:r.join(","),'" group-id')),this.hls.trigger(ee.SUBTITLE_TRACKS_UPDATED,c),-1!==u&&-1===this.trackId&&this.setSubtitleTrack(u)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i<t.length;i++){var n=t[i];if((!r||n.default)&&(r||e)&&(!e||zt(n,e)))return i}if(e){for(var a=0;a<t.length;a++){var s=t[a];if(ls(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if(ls(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1}},{key:"findTrackForTextTrack",value:function(e){if(e)for(var t=this.tracksInGroup,r=0;r<t.length;r++){if(us(t[r],e))return r}return-1}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&(t.context.type!==ne||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}},{key:"setSubtitleOption",value:function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&zt(e,r))return r;var i=qt(e,this.tracksInGroup);if(i>-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}if(r)return null;var a=qt(e,t);if(a>-1)return t[a]}}return null}},{key:"loadPlaylist",value:function(e){E(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}},{key:"loadingPlaylist",value:function(e,r){E(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ee.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this.media;if(e){var t,r=Ro(e.textTracks),i=this.currentTrack;if(i&&((t=r.filter(function(e){return us(i,e)})[0])||this.warn('Unable to find subtitle TextTrack with name "'.concat(i.name,'" and language "').concat(i.lang,'"'))),[].slice.call(r).forEach(function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")}),t){var n=this.subtitleDisplay?"showing":"hidden";t.mode!==n&&(t.mode=n)}}}},{key:"setSubtitleTrack",value:function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!X(e))this.warn("Invalid subtitle track id: ".concat(e));else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),i){var n=!!i.details&&!i.details.live;if(e!==this.trackId||i!==r||!n){this.log("Switching to subtitle-track ".concat(e)+(i?' "'.concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId):""));var a=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,c=i.url;this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:c});var d=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(d)}}else this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e}}])}(ss);function Po(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var xo=.025,Do=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Co(e,t,r){return"".concat(e.identifier,"-").concat(r+1,"-").concat(Po(t))}var _o=function(){return o(function e(t,r){a(this,e),this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)},[{key:"setDateRange",value:function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}},{key:"reset",value:function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}},{key:"isAssetPastPlayoutLimit",value:function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)}},{key:"findAssetIndex",value:function(e){return this.assetList.indexOf(e)}},{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Mo(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-Mo(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=X(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Mo(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<xo))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Do.Range:Do.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}},{key:"toString",value:function(){return'["'.concat((e=this).identifier,'" ').concat(e.cue.pre?"<pre>":e.cue.post?"<post>":"").concat(e.timelineStart.toFixed(2),"-").concat(e.resumeTime.toFixed(2),"]");var e}}])}();function Mo(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<xo)?t.start:t.start+t.duration}function Oo(e,t,r){var i=new self.URL(e,r);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",t),i}function Fo(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function No(e){var t=e.timelineStart,r=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+r).toFixed(2),"]")}var Uo=function(){return o(function e(t,r,i,n){var s=this;a(this,e),this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){s.reachedPlayout(s.currentTime)&&s.hls&&s.hls.trigger(ee.PLAYOUT_LIMIT_REACHED,{})};var o=this.hls=new t(r);this.interstitial=i,this.assetItem=n;var l=function(){s.hasDetails=!0};o.once(ee.LEVEL_LOADED,l),o.once(ee.AUDIO_TRACK_LOADED,l),o.once(ee.SUBTITLE_TRACK_LOADED,l),o.on(ee.MEDIA_ATTACHING,function(e,t){var r=t.media;s.removeMediaListeners(),s.mediaAttached=r,s.interstitial.playoutLimit&&(r.addEventListener("timeupdate",s.checkPlayout),s.appendInPlace&&o.on(ee.BUFFER_APPENDED,function(){var e=s.bufferedEnd;s.reachedPlayout(e)&&(s._bufferedEosTime=e,o.trigger(ee.BUFFERED_TO_END,void 0))}))})},[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"loadSource",value:function(){var e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{var t=this.assetItem.uri;try{t=Oo(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}},{key:"bufferedInPlaceToEnd",value:function(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;var r=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,n=jr.bufferInfo(e,i,0);return this.getAssetTime(n.end)>=r-.02}},{key:"reachedPlayout",value:function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=jr.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r<e)return r}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}},{key:"getAssetTime",value:function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}},{key:"removeMediaListeners",value:function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}},{key:"bufferSnapShot",value:function(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}},{key:"destroy",value:function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}},{key:"attachMedia",value:function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}},{key:"detachMedia",value:function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.hls)||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.hls)||e.pauseBuffering()}},{key:"transferMedia",value:function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}},{key:"resetDetails",value:function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}},{key:"on",value:function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)}},{key:"once",value:function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)}},{key:"off",value:function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)}},{key:"toString",value:function(){var e;return"HlsAssetPlayer: ".concat(No(this.assetItem)," ").concat(null==(e=this.hls)?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}])}(),Bo=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["interstitials-sched",r])).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=e,i}return d(t,e),o(t,[{key:"destroy",value:function(){this.reset(),this.onScheduleUpdate=null}},{key:"reset",value:function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(function(e){return e.reset()}),this.events=this.items=null}},{key:"resetErrorsInRange",value:function(e,t){return this.events?this.events.reduce(function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r},0):0}},{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"getEvent",value:function(e){return e&&this.eventMap[e]||null}},{key:"hasEvent",value:function(e){return e in this.eventMap}},{key:"findItemIndex",value:function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r}},{key:"findItemIndexAtTime",value:function(e,t){var r=this.items;if(r)for(var i=0;i<r.length;i++){var n=r[i];if(t&&"primary"!==t&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return i}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var r=this.items;if(r)for(var i=e;i<=t&&r[i];i++){var n=r[i].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return i}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return-1}},{key:"findAssetIndex",value:function(e,t){var r=e.assetList,i=r.length;if(i>1)for(var n=0;n<i;n++){var a=r[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===i-1))return n}}return 0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var r=t.assetList,i=r[r.length-1];if(i)return i.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var r=this,i=e.main.details,n=i.dateRanges,a=this.events,s=this.parseDateRanges(n,{url:i.url},t),o=Object.keys(n),l=a?a.filter(function(e){return!o.includes(e.identifier)}):[];s.length&&s.sort(function(e,t){var r=e.cue.pre,i=e.cue.post,n=t.cue.pre,a=t.cue.post;if(r&&!n)return-1;if(n&&!r)return 1;if(i&&!a)return 1;if(a&&!i)return-1;if(!(r||n||i||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=s,l.forEach(function(e){r.removeEvent(e)}),this.updateSchedule(e,l)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=this.events||[];if(i.length||t.length||this.length<2){var n=this.items,a=this.parseSchedule(i,e);(r||t.length||(null==n?void 0:n.length)!==a.length||a.some(function(e,t){return Math.abs(e.playout.start-n[t].playout.start)>.005||Math.abs(e.playout.end-n[t].playout.end)>.005}))&&(this.items=a,this.onScheduleUpdate(t,n))}}},{key:"parseDateRanges",value:function(e,t,r){for(var i=[],n=Object.keys(e),a=0;a<n.length;a++){var s=n[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new _o(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),i.push(l)}}return i}},{key:"parseSchedule",value:function(e,t){var r=[],i=t.main.details,n=i.live?1/0:i.edge,a=0;if((e=e.filter(function(e){return!(e.error||e.cue.once&&e.hasPlayed)})).length){this.resolveOffsets(e,t);var s=0,o=0;if(e.forEach(function(t,i){var l=t.cue.pre,u=t.cue.post,c=e[i-1]||null,d=t.appendInPlace,h=u?n:t.startOffset,f=t.duration,v=t.timelineOccupancy===Do.Range?f:0,g=t.resumptionOffset,p=(null==c?void 0:c.startTime)===h,m=h+t.cumulativeDuration,y=d?m+f:h+g;if(l||!u&&h<=0){var E=o;o+=v,t.timelineStart=m;var k=a;a+=f,r.push({event:t,start:m,end:y,playout:{start:k,end:a},integrated:{start:E,end:o}})}else{if(!(h<=n))return;if(!p){var T=h-s;if(T>.033){var S=s,b=o;o+=T;var A=a;a+=T;var L={previousEvent:e[i-1]||null,nextEvent:t,start:S,end:S+T,playout:{start:A,end:a},integrated:{start:b,end:o}};r.push(L)}else T>0&&c&&(c.cumulativeDuration+=T,r[r.length-1].end=h)}u&&(y=m),t.timelineStart=m;var I=o;o+=v;var R=a;a+=f,r.push({event:t,start:m,end:y,playout:{start:R,end:a},integrated:{start:I,end:o}})}var w=t.resumeTime;s=u||w>n?n:w}),s<n){var l,u=s,c=o,d=n-s;o+=d;var h=a;a+=d,r.push({previousEvent:(null==(l=r[r.length-1])?void 0:l.event)||null,nextEvent:null,start:s,end:u+d,playout:{start:h,end:a},integrated:{start:c,end:o}})}this.setDurations(n,a,o)}else{r.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n)}return r}},{key:"setDurations",value:function(e,t,r){this.durations={primary:e,playout:t,integrated:r}}},{key:"resolveOffsets",value:function(e,t){var r=this,i=t.main.details,n=i.live?1/0:i.edge,a=0,s=-1;e.forEach(function(o,l){var u=o.cue.pre,c=o.cue.post,d=u?0:c?n:o.startTime;(r.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=er(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(r.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1));!o.appendInPlace&&l+1<e.length&&(e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event ".concat(o))));var h=X(o.resumeOffset)?o.resumeOffset:o.duration;a+=h})}},{key:"primaryCanResumeInPlaceAt",value:function(e,t){var r=this,i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>xo?(this.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with estimated timeline end ").concat(n)),!1):!Object.keys(t).some(function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," past ").concat(n," playlist end ").concat(s)),!1;var o=er(null,a.fragments,i);if(!o)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," does not align with any fragments in ").concat(n," playlist (").concat(a.fragStart,"-").concat(a.fragmentEnd,")")),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)<xo+l||Math.abs(o.end-i)<xo+l)&&(r.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with ").concat(n," fragment bounds (").concat(o.start,"-").concat(o.end," sn: ").concat(o.sn," cc: ").concat(o.cc,")")),!0)})}},{key:"updateAssetDurations",value:function(e){if(e.assetListLoaded){for(var t=e.timelineStart,r=0,i=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,i||(i=null===s.duration),n||(n=!!s.error),r+=s.error?0:s.duration||0}e.duration=i&&!n?Math.max(r,e.duration):r}}},{key:"removeEvent",value:function(e){e.reset(),delete this.eventMap[e.identifier]}}])}(ve);function Go(e){return"[".concat(e.event?'"'+e.event.identifier+'"':"primary",": ").concat(e.start.toFixed(2),"-").concat(e.end.toFixed(2),"]")}var Ho=function(){return o(function e(t){a(this,e),this.hls=void 0,this.hls=t},[{key:"destroy",value:function(){this.hls=null}},{key:"loadAssetList",value:function(e,t){var r,i=this,n=e.assetListUrl;try{r=Oo(n,this.hls.sessionId,e.baseUrl)}catch(t){var a=this.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(ee.ERROR,a)}t&&"data:"!==r.protocol&&r.searchParams.set("_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,r,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,i.hls.trigger(ee.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=i.assignAssetListError(e,Z.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,a);i.hls.trigger(ee.ERROR,l)}},onError:function(t,r,n,a){var s=i.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(r.url,")")),r.url,a,n);i.hls.trigger(ee.ERROR,s)},onTimeout:function(t,r,n){var a=i.assignAssetListError(e,Z.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(r.url,")")),r.url,t,n);i.hls.trigger(ee.ERROR,a)}};return o.load(l,c,d),this.hls.trigger(ee.ASSET_LIST_LOADING,{event:e}),o}},{key:"assignAssetListError",value:function(e,t,r,i,n,a){return e.error=r,{type:J.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:r,networkDetails:a,stats:n}}}])}();function Vo(e){var t;null==e||null==(t=e.play())||t.catch(function(){})}function Ko(e,t){return"[".concat(e,"] Advancing timeline position to ").concat(t)}var jo=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,i.hls=void 0,i.assetListLoader=void 0,i.mediaSelection=null,i.altSelection=null,i.media=null,i.detachedData=null,i.requiredTracks=null,i.manager=null,i.playerQueue=[],i.bufferedPos=-1,i.timelinePos=-1,i.schedule=void 0,i.playingItem=null,i.bufferingItem=null,i.waitingItem=null,i.endedItem=null,i.playingAsset=null,i.endedAsset=null,i.bufferingAsset=null,i.shouldPlay=!1,i.onPlay=function(){i.shouldPlay=!0},i.onPause=function(){i.shouldPlay=!1},i.onSeeking=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&i.schedule){var t=e-i.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;i.timelinePos=e,i.bufferedPos=e;var n=i.playingItem;if(n){if(r)i.schedule.resetErrorsInRange(e,e-t)&&i.updateSchedule(!0);if(i.checkBuffer(),r&&e<n.start||e>=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked ".concat(r?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(r&&e<d||e>=d+h)null!=(c=n.event)&&c.appendInPlace&&(i.clearInterstitial(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u)}else if(i.playingLastItem&&i.isInterstitial(n)){var f=n.event.assetList[0];f&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,f))}}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&e>i.timelinePos){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;if(n)e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return Go(e)})," pos: ").concat(i.timelinePos)),l.length&&i.log("Removed events ".concat(l));var c=null,d=null;n&&(c=i.updateItem(n,i.timelinePos),i.itemsMatch(n,c)?i.playingItem=c:i.waitingItem=i.endedItem=null),i.waitingItem=i.updateItem(i.waitingItem),i.endedItem=i.updateItem(i.endedItem);var h=i.bufferingItem;if(h&&(d=i.updateItem(h,i.bufferedPos),i.itemsMatch(h,d)?i.bufferingItem=d:h.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){i.clearAssetPlayer(e.identifier,null)})}),i.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>xo&&i.warn("".concat(n,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(i.hls.trigger(ee.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.includes(n.event.identifier))return i.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),void i.primaryFallback(n.event);n&&i.trimInPlace(c,n),h&&d!==c&&i.trimInPlace(d,h),i.checkBuffer()}}},i.hls=e,i.HlsPlayerClass=r,i.assetListLoader=new Ho(e),i.schedule=new Bo(i.onScheduleUpdate,e.logger),i.registerListeners(),i}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(ee.MEDIA_ENDED,this.onMediaEnded,this),e.on(ee.ERROR,this.onError,this),e.on(ee.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(ee.MEDIA_ENDED,this.onMediaEnded,this),e.off(ee.ERROR,this.onError,this),e.off(ee.DESTROYING,this.onDestroying,this))}},{key:"startLoad",value:function(){this.resumeBuffering()}},{key:"stopLoad",value:function(){this.pauseBuffering()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}},{key:"onDestroying",value:function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}},{key:"removeMediaListeners",value:function(e){un(e,"play",this.onPlay),un(e,"pause",this.onPause),un(e,"seeking",this.onSeeking),un(e,"timeupdate",this.onTimeupdate)}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;ln(r,"seeking",this.onSeeking),ln(r,"timeupdate",this.onTimeupdate),ln(r,"play",this.onPlay),ln(r,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}}},{key:"clearScheduleState",value:function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and ".concat(n)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}},{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==Do.Point){var c=r(a);(null==c?void 0:c.interstitial)===u&&(l+=c.assetItem.startOffset+c[o])}}else l+=("bufferedPos"===s?n():e[s])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,i;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},s=function(t,n){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to ".concat(t,' "').concat(n,'"'));var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,n),c=null==(s=e.schedule.items)?void 0:s[u],d=e.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,v=l&&e.itemsMatch(l,c);if(l&&(f||v)){var g=r(e.playingAsset),p=(null==g?void 0:g.media)||e.primaryMedia;if(p){var m="primary"===n?p.currentTime:i(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-m,E=(f?m:p.currentTime)+y;if(E>=0&&(!g||f||E<=g.duration))return void(p.currentTime=E)}}if(c){var k=t;if("primary"!==n){var T=t-c[n].start;k=c.start+T}var S=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!S&&!c.event.appendInPlace){if(l){var b=e.findItemIndex(l);if(u>b){var A=e.schedule.findJumpRestrictedIndex(b+1,u);if(A>b)return void e.setSchedulePosition(A)}var L=0;if(S)e.timelinePos=k,e.checkBuffer();else for(var I=c.event.assetList,R=t-(c[n]||c).start,w=I.length;w--;){var P=I[w];if(P.duration&&R>=P.startOffset&&R<P.startOffset+P.duration){L=w;break}}e.setSchedulePosition(u,L)}}else{var x=e.media||(f?null==d?void 0:d.media:null);x&&(x.currentTime=k)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){var r,n=t(),a=e.bufferingItem;return a&&a===n&&(i(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(r=e.bufferingAsset)?void 0:r.startOffset))||0},get currentTime(){var t=o(),r=e.effectivePlayingItem;return r&&r===t?i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),i=e.effectivePlayingItem;i&&i===r&&s(t+i.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,r=null==(t=o())?void 0:t.event.assetList;return r?r.map(function(t){return e.getAssetPlayer(t.identifier)}):[]},get playingIndex(){var t,r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){var t;return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&X(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"isInterstitial",value:function(e){return!(null==e||!e.event)}},{key:"retreiveMediaSource",value:function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(Kt(n))),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}},{key:"transferMediaTo",value:function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else if(c){var d=this.getBufferingPlayer();d?(s=d.transferMedia(),a="".concat(d)):a="detached MediaSource"}else a="detached media";if(!s)if(c)s=this.detachedData,this.log("using detachedData: MediaSource ".concat(Kt(s)));else if(!this.detachedData||o.media===t){var h=this.playerQueue;h.length>1&&h.forEach(function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets ".concat(t))}}),this.hls.detachMedia(),this.detachedData={media:t}}var f=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState),v=f&&s?s:t;this.log("".concat(f?"transfering MediaSource":"attaching media"," to ").concat(l?e:"Primary"," from ").concat(a," (media.currentTime: ").concat(t.currentTime,")"));var g=this.schedule;if(v===s&&g){var p=l&&e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:!l||p,cueRemoval:!l}}e.attachMedia(v)}}},{key:"onInterstitialCueEnter",value:function(){this.onTimeupdate()}},{key:"checkStart",value:function(){var e=this.schedule,t=null==e?void 0:e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var r=this.timelinePos,i=this.effectivePlayingItem;if(-1===r){var n=this.hls.startPosition;if(this.log(Ko("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){var a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){var s=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(s);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){var l=e.findItemIndex(i);this.setSchedulePosition(l)}}}},{key:"advanceAssetBuffering",value:function(e,t){var r=e.event,i=r.findAssetIndex(t),n=Fo(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(e)+1];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(e,n)}},{key:"advanceAfterAssetEnded",value:function(e,t,r){var i=Fo(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=t+1;if(a>=n.length)return void this.setSchedulePosition(-1);var s=e.resumeTime;this.timelinePos<s&&(this.log(Ko("advanceAfterAssetEnded",s)),this.timelinePos=s,e.appendInPlace&&this.advanceInPlace(s),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){var o=e.assetList[i];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(t,i)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var r=this.schedule;if(r){var i=t.parentIdentifier,n=r.getEvent(i);if(n){var a=r.findEventIndex(i),s=r.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;if(i&&!this.playbackDisabled){var n=e>=0?i[e]:null;this.log("setSchedulePosition ".concat(e,", ").concat(t," (").concat(n?Go(n):n,") pos: ").concat(this.timelinePos));var a=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(a)){var o=a.event,l=this.playingAsset,u=null==l?void 0:l.identifier,c=u?this.getAssetPlayer(u):null;if(c&&u&&(!this.eventItemsMatch(a,n)||void 0!==t&&u!==o.assetList[t].identifier)){var d,h=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED ".concat(h+1,"/").concat(o.assetList.length," ").concat(No(l))),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(ee.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:h,event:o,schedule:i.slice(0),scheduleIndex:e,player:c}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),h));this.retreiveMediaSource(u,n),!c.media||null!=(d=this.detachedData)&&d.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log("INTERSTITIAL_ENDED ".concat(o," ").concat(Go(a))),o.hasPlayed=!0,this.hls.trigger(ee.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once)){var f;this.updateSchedule();var v=null==(f=this.schedule)?void 0:f.items;if(n&&v){var g=this.findItemIndex(n);this.advanceSchedule(g,v,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(i<e||i>e+1)&&a.clearInterstitial(r,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===r){var d=Fo(c,(r=s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,r);r=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,r);if(this.eventItemsMatch(o,h||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED ".concat(Go(o)," ").concat(c.appendInPlace?"append in place":"")),this.hls.trigger(ee.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading ".concat(c));if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial ".concat(c));this.waitingItem=this.endedItem=null,this.playingItem=o;var v=c.assetList[r];if(!v)return void this.advanceAfterAssetEnded(c,e,r||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(r+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,r,t,e,l),this.shouldPlay&&Vo(f.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Vo(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"resumePrimary",value:function(e,t,r){var i,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming ".concat(Go(e))),null==(i=this.detachedData)||!i.mediaSource){var a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Ko("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(r){var s=null==(n=this.schedule)?void 0:n.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(Go(e))),this.hls.trigger(ee.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}}},{key:"getPrimaryResumption",value:function(e,t){var r=e.start;if(this.primaryLive){var i=this.primaryDetails;if(0===t)return this.hls.startPosition;if(i&&(r<i.fragmentStart||r>i.edge))return this.hls.liveSyncPosition||-1}return r}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:jr.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Ko("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var r,i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(r=i.mainForwardBufferInfo)?void 0:r.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}},{key:"onManifestLoading",value:function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ee.BUFFER_CODECS,this.onBufferCodecs,this)}},{key:"onLevelUpdated",value:function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=fe(fe({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var r=this.hls.audioTracks[t.id],i=this.mediaSelection;if(i){var n=fe(fe({},i),{},{audio:r});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{audio:r})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var r=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(i){var n=fe(fe({},i),{},{subtitles:r});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{subtitles:r})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=Wt(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setAudioOption(t)||i.setAudioOption(r))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r=Wt(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setSubtitleOption(t)||-1!==t.id&&i.setSubtitleOption(r))})}},{key:"onBufferCodecs",value:function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var r=0;r<t.length;r++){var i=t[r];if(i.cue.post){var n,a=this.schedule.findEventIndex(i.identifier),s=null==(n=this.schedule.items)?void 0:n[a];this.isInterstitial(s)&&this.eventItemsMatch(s,this.bufferingItem)&&this.bufferedToItem(s,0);break}}this.bufferedPos=Number.MAX_VALUE}}}},{key:"onMediaEnded",value:function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;return e&&i&&i[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var r=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)});var i=e.end+.25,n=jr.bufferInfo(this.primaryMedia,i,0);if(n.end>i||(n.nextStart||0)>i){this.log("trim buffered interstitial ".concat(Go(e)," (was ").concat(Go(t),")"));this.attachPrimary(i,null,!0),this.flushFrontBuffer(i)}}}},{key:"itemsMatch",value:function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}},{key:"eventItemsMatch",value:function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}},{key:"findItemIndex",value:function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}},{key:"updateSchedule",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=this.mediaSelection;r&&(null==(e=this.schedule)||e.updateSchedule(r,[],t))}},{key:"checkBuffer",value:function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=jr.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}}},{key:"updateBufferedPos",value:function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),d=t[c];if((-1===o&&n&&e>=n.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=c),this.isInterstitial(n)){var h=n.event;if(c-s>1&&!1===h.appendInPlace)return;if(0===h.assetList.length&&h.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else r&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var r=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var i=r.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,r=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,r)&&i){var n=i.items,a=i.events;if(!n||!a)return r;var s=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(Go(e))+(r?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,r){var i=t.getAssetPlayer(e.identifier);i&&(r===u&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(function(e){return e.pauseBuffering()});this.hls.trigger(ee.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;var i=this.detachedData;if(i)if(i.mediaSource){this.attachPrimary(e.start,e,!0)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}},{key:"preloadPrimary",value:function(e){var t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}},{key:"bufferedToEvent",value:function(e,t){var r=e.event,i=0===r.assetList.length&&!r.assetListLoader,n=r.cue.once;if(i||!n){var a=this.preloadAssets(r,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var r=e.assetUrl,i=e.assetList.length,n=0===i&&!e.assetListLoader,a=e.cue.once;if(n){var s,o=e.timelineStart;if(e.appendInPlace){var l,u=this.playingItem;this.isInterstitial(u)||(null==u||null==(l=u.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var c=0;if(!this.playingItem&&this.primaryLive&&-1===(c=this.hls.startPosition)&&(c=this.hls.liveSyncPosition||0),c&&!e.cue.pre&&!e.cue.post){var d=c-o;d>0&&(s=Math.round(1e3*d)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(r?1:i," ").concat(e).concat(s?" live-start: ".concat(c," start-offset: ").concat(s):"")),r)return this.createAsset(e,0,0,o,e.duration,r);var h=this.assetListLoader.loadAssetList(e,s);h&&(e.assetListLoader=h)}else if(!a&&i){for(var f=t;f<i;f++){var v=e.assetList[f],g=this.getAssetPlayerQueueIndex(v.identifier);-1!==g&&!this.playerQueue[g].destroyed||v.error||this.createAssetPlayer(e,v,f)}var p=e.assetList[t];if(p){var m=this.getAssetPlayer(p.identifier);return m&&m.loadSource(),m}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,r=this.requiredTracks;r&&(this.log("Removing front buffer starting at ".concat(e)),Object.keys(r).forEach(function(r){t.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})}))}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}},{key:"getAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}},{key:"getBufferingPlayer",value:function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}},{key:"createAsset",value:function(e,t,r,i,n,a){var s={parentIdentifier:e.identifier,identifier:Co(e,a,t),duration:n,startOffset:r,timelineStart:i,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,r){var i=this,n=this.hls,a=n.userConfig,s=a.videoPreference,o=n.loadLevelObj||n.levels[n.currentLevel];(s||o)&&(s=de({},s),o.videoCodec&&(s.videoCodec=o.videoCodec),o.videoRange&&(s.allowedVideoRanges=[o.videoRange]));var l=n.audioTracks[n.audioTrack],u=n.subtitleTracks[n.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){var d=this.timelinePos-t.timelineStart;if(d>1){var h=t.duration;h&&d<h&&(c=d)}}var f=t.identifier,v=fe(fe({},a),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:f,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:l||a.audioPreference,subtitlePreference:u||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var g=v.cmcd;null!=g&&g.sessionId&&g.contentId&&(v.cmcd=de({},g,{contentId:Po(t.uri)})),this.getAssetPlayer(f)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(f));var p=new Uo(this.HlsPlayerClass,v,e,t);this.playerQueue.push(p),e.assetList[r]=t;var m=!0,y=function(n){if(n.live){var a,s=new Error("Interstitials MUST be VOD assets ".concat(e)),o={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:s},l=(null==(a=i.schedule)?void 0:a.findEventIndex(e.identifier))||-1;i.handleAssetItemError(o,e,l,r,s.message)}else{var u=n.edge-n.fragmentStart,c=t.duration;(m||null===c||u>c)&&(m=!1,i.log('Interstitial asset "'.concat(f,'" duration change ').concat(c," > ").concat(u)),t.duration=u,i.updateSchedule())}};p.on(ee.LEVEL_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(ee.LEVEL_PTS_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(ee.EVENT_CUE_ENTER,function(){return i.onInterstitialCueEnter()});var E=function(e,t){var r=i.getAssetPlayer(f);if(r&&t.tracks){r.off(ee.BUFFER_CODECS,E),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};p.on(ee.BUFFER_CODECS,E);p.on(ee.BUFFERED_TO_END,function(){var r,n=i.getAssetPlayer(f);if(i.log("buffered to end of asset ".concat(n)),n&&i.schedule){var a=i.schedule.findEventIndex(e.identifier),s=null==(r=i.schedule.items)?void 0:r[a];i.isInterstitial(s)&&i.advanceAssetBuffering(s,t)}});var k=function(t){return function(){if(i.getAssetPlayer(f)&&i.schedule){i.shouldPlay=!0;var r=i.schedule.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return p.once(ee.MEDIA_ENDED,k(r)),p.once(ee.PLAYOUT_LIMIT_REACHED,k(1/0)),p.on(ee.ERROR,function(t,n){if(i.schedule){var a=i.getAssetPlayer(f);if(n.details===Z.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,"Asset player error ".concat(n.error," ").concat(e))}}),p.on(ee.DESTROYING,function(){if(i.getAssetPlayer(f)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly ".concat(f)),n={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(No(t))),this.hls.trigger(ee.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p}},{key:"clearInterstitial",value:function(e,t){var r=this;e.assetList.forEach(function(e){r.clearAssetPlayer(e.identifier,t)}),e.reset()}},{key:"resetAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'.concat(e,'" after error'));var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear ".concat(i," toSegment: ").concat(t?Go(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,u&&u.identifier===o||(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(No(s))),this.hls.trigger(ee.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)}},{key:"bufferAssetPlayer",value:function(e,t){var r,i;if(this.schedule){var n=e.interstitial,a=e.assetItem,s=this.schedule.findEventIndex(n.identifier),o=null==(r=this.schedule.items)?void 0:r[s];if(o){e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=a;var l=this.getBufferingPlayer();if(l!==e){var u=n.appendInPlace;if(!u||!1!==(null==l?void 0:l.interstitial.appendInPlace)){var c=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering ".concat(e));if(c&&!Se(c,e.tracks)){var d=new Error("Asset ".concat(No(a)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(c),"')")),h={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=n.findAssetIndex(a);return void this.handleAssetItemError(h,n,s,f,d.message)}}this.transferMediaTo(e,t)}}}}}},{key:"handleInPlaceStall",value:function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at ".concat(o," of ").concat(o+l," in ").concat(s," ").concat(e," (media.currentTime: ").concat(i,")")),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}}},{key:"advanceInPlace",value:function(e){var t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}},{key:"handleAssetItemError",value:function(e,t,r,i,n){if(e.details!==Z.BUFFER_STALLED_ERROR){var a=t.assetList[i]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?No(a):a," ").concat(e.error)),this.schedule){var s=(null==a?void 0:a.identifier)||"",o=this.getAssetPlayerQueueIndex(s),l=this.playerQueue[o]||null,u=this.schedule.items,c=de({},e,{fatal:!1,errorAction:Tr(!0),asset:a,assetListIndex:i,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(ee.INTERSTITIAL_ASSET_ERROR,c),e.fatal){var d=this.playingAsset,h=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(s,null),a.error=f),t.assetList.some(function(e){return!e.error}))for(var v=i;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===s?this.advanceAfterAssetEnded(t,r,i):h&&h.identifier===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,r=this.effectivePlayingItem;if(r){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(this.timelinePos," playing: ").concat(Go(r)," error: ").concat(e.error));var i=this.timelinePos;-1===i&&(i=this.hls.startPosition);var n=this.updateItem(r,i);if(this.itemsMatch(r,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;var a=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(a)}else this.checkStart()}},{key:"onAssetListLoaded",value:function(e,t){var r,i,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(r=this.schedule)&&r.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var r=parseFloat(e.DURATION);n.createAsset(a,t,c,l+c,r,e.URI),c+=r}),a.duration=c,this.log("Loaded asset-list with duration: ".concat(c," (was: ").concat(u,") ").concat(a));var d=this.waitingItem,h=(null==d?void 0:d.event.identifier)===s;this.updateSchedule();var f=null==(i=this.bufferingItem)?void 0:i.event;if(h){var v,g=this.schedule.findEventIndex(s),p=null==(v=this.schedule.items)?void 0:v[g];if(p){if(!this.playingItem&&this.timelinePos>p.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return a.error=new Error("Interstitial no longer within playback range ".concat(this.timelinePos," ").concat(a)),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(p)}this.setSchedulePosition(g)}else if((null==f?void 0:f.identifier)===s){var m=a.assetList[0];if(m){var y=this.getAssetPlayer(m.identifier);if(f.appendInPlace){var E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}}},{key:"onError",value:function(e,t){if(this.schedule)switch(t.details){case Z.ASSET_LIST_PARSING_ERROR:case Z.ASSET_LIST_LOAD_ERROR:case Z.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case Z.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);this.log("Primary player stall @".concat(this.timelinePos," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(ve),Yo=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"subtitle-stream-controller",oe])).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s.registerListeners(),s}return d(t,e),o(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),E(t,"onHandlerDestroying",this,3)([]),this.mainDetails=null}},{key:"registerListeners",value:function(){E(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"unregisterListeners",value:function(){E(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"startLoad",value:function(e,t){this.stopLoad(),this.state=hn,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"onManifestLoading",value:function(){E(t,"onManifestLoading",this,3)([]),this.mainDetails=null}},{key:"onMediaDetaching",value:function(e,r){this.tracksBuffered=[],E(t,"onMediaDetaching",this,3)([e,r])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var r=t.frag,i=t.success;if(this.fragContextChanged(r)||(Oe(r)&&(this.fragPrevious=r),this.state=hn),i){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=r.start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(function(e){for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}}),this.fragmentTracker.removeFragmentsInRange(r,n,oe)}}},{key:"onError",value:function(e,t){var r=t.frag;(null==r?void 0:r.type)===oe&&(t.details===Z.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dn&&(this.state=hn))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks;this.levels&&os(this.levels,i)?this.levels=i.map(function(e){return new Gt(e)}):(this.tracksBuffered=[],this.levels=i.map(function(e){var t=new Gt(e);return r.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,oe),this.fragPrevious=null,this.mediaBuffer=null)}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r;if(this.currentTrackId=t.id,null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==dn&&this.setInterval(500)}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r,i=this.currentTrackId,n=this.levels,a=t.details,s=t.id;if(n){var o=n[s];if(!(s>=n.length)&&o){this.log("Subtitle track ".concat(s," loaded [").concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;var u=this.mainDetails;if(!u)return void(this.startFragRequested=!1);var c,d=u.fragments[0];if(o.details)0===(l=this.alignPlaylists(a,o.details,null==(c=this.levelLastLoaded)?void 0:c.details))&&d&&zi(a,l=d.start);else a.hasProgramDateTime&&u.hasProgramDateTime?(on(a,u),l=a.fragmentStart):d&&zi(a,l=d.start);u&&!this.startFragRequested&&this.setStartPosition(u,l)}if(o.details=a,this.levelLastLoaded=o,s===i)if(this.hls.trigger(ee.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===hn)er(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}else this.warn("Subtitle tracks were reset while loading level ".concat(s))}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this,r=e.frag,i=e.payload,n=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&i&&i.byteLength>0&&null!=n&&n.key&&n.iv&&ai(n.method)){var s=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,si(n.method)).catch(function(e){throw a.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e}).then(function(e){var t=performance.now();a.trigger(ee.FRAG_DECRYPTED,{frag:r,payload:e,stats:{tstart:s,tdecrypt:t}})}).catch(function(e){t.warn("".concat(e.name,": ").concat(e.message)),t.state=hn})}}},{key:"doTick",value:function(){if(this.media){if(this.state===hn){var e=this.currentTrackId,t=this.levels,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;if(this.waitForLive(r))return;var i=this.config,n=this.getLoadPosition(),a=jr.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),s=a.end,o=a.len,l=r.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var u=l.fragments,c=u.length,d=l.edge,h=null,f=this.fragPrevious;if(s<d){var v=i.maxFragLookUpTolerance,g=s>d-v?0:v;!(h=er(f,u,Math.max(u[0].start,s),g))&&f&&f.start<u[0].start&&(h=u[0])}else h=u[c-1];if(!(h=this.filterReplacedPrimary(h,r.details)))return;var p=u[h.sn-l.startSN-1];if(p&&p.cc===h.cc&&this.fragmentTracker.getState(p)===Sr&&(h=p),this.fragmentTracker.getState(h)===Sr){var m=this.mapToInitFragWhenRequired(h);m&&this.loadFragment(m,r,s)}}}else this.state=hn}},{key:"loadFragment",value:function(e,r,i){Oe(e)?E(t,"loadFragment",this,3)([e,r,i]):this._loadInitSegment(e,r)}},{key:"mediaBufferTimeRanges",get:function(){return new Wo(this.tracksBuffered[this.currentTrackId]||[])}}])}(bn),Wo=o(function e(t){a(this,e),this.buffered=void 0;var r=function(e,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(r,") is greater than the maximum bound (").concat(i,")"));return t[r][e]};this.buffered={get length(){return t.length},end:function(e){return r("end",e,t.length)},start:function(e){return r("start",e,t.length)}}}),qo={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},zo=function(e){return String.fromCharCode(qo[e]||e)},Xo=15,Qo=100,$o={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Jo={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Zo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},el={25:2,26:4,29:6,30:8,31:10,27:13,28:15},tl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],rl=function(){return o(function e(){a(this,e),this.time=null,this.verboseLevel=0},[{key:"log",value:function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;ke.log("".concat(this.time," [").concat(e,"] ").concat(r))}}}])}(),il=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},nl=function(){return o(function e(){a(this,e),this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},[{key:"reset",value:function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}},{key:"setStyles",value:function(e){for(var t=["foreground","underline","italics","background","flash"],r=0;r<t.length;r++){var i=t[r];e.hasOwnProperty(i)&&(this[i]=e[i])}}},{key:"isDefault",value:function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}},{key:"equals",value:function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}},{key:"copy",value:function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}])}(),al=function(){return o(function e(){a(this,e),this.uchar=" ",this.penState=new nl},[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.copy(t)}},{key:"setPenState",value:function(e){this.penState.copy(e)}},{key:"equals",value:function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.copy(e.penState)}},{key:"isEmpty",value:function(){return" "===this.uchar&&this.penState.isDefault()}}])}(),sl=function(){return o(function e(t){a(this,e),this.chars=[],this.pos=0,this.currPenState=new nl,this.cueStartTime=null,this.logger=void 0;for(var r=0;r<Qo;r++)this.chars.push(new al);this.logger=t},[{key:"equals",value:function(e){for(var t=0;t<Qo;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}},{key:"copy",value:function(e){for(var t=0;t<Qo;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Qo;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}},{key:"setCursor",value:function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Qo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Qo)}},{key:"moveCursor",value:function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){var t=this;e>=144&&this.backSpace();var r=zo(e);this.pos>=Qo?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))}},{key:"clearFromPos",value:function(e){var t;for(t=e;t<Qo;t++)this.chars[t].reset()}},{key:"clear",value:function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{key:"clearToEndOfRow",value:function(){this.clearFromPos(this.pos)}},{key:"getTextString",value:function(){for(var e=[],t=!0,r=0;r<Qo;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}])}(),ol=function(){return o(function e(t){a(this,e),this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var r=0;r<Xo;r++)this.rows.push(new sl(t));this.logger=t},[{key:"reset",value:function(){for(var e=0;e<Xo;e++)this.rows[e].clear();this.currRow=14}},{key:"equals",value:function(e){for(var t=!0,r=0;r<Xo;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<Xo;t++)this.rows[t].copy(e.rows[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Xo;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}},{key:"backSpace",value:function(){this.rows[this.currRow].backSpace()}},{key:"clearToEndOfRow",value:function(){this.rows[this.currRow].clearToEndOfRow()}},{key:"insertChar",value:function(e){this.rows[this.currRow].insertChar(e)}},{key:"setPen",value:function(e){this.rows[this.currRow].setPenStyles(e)}},{key:"moveCursor",value:function(e){this.rows[this.currRow].moveCursor(e)}},{key:"setCursor",value:function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}},{key:"setPAC",value:function(e){this.logger.log(2,function(){return"pacData = "+Kt(e)});var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<Xo;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[i].cueStartTime,s=this.logger.time;if(null!==a&&null!==s&&a<s)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[i+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);l.setCursor(e.indent),e.color=l.chars[c].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)}},{key:"setBkgData",value:function(e){this.logger.log(2,function(){return"bkgData = "+Kt(e)}),this.backSpace(),this.setPen(e),this.insertChar(32)}},{key:"setRollUpRows",value:function(e){this.nrRollUpRows=e}},{key:"rollUp",value:function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,function(){return e.getDisplayText()});var t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")}},{key:"getDisplayText",value:function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<Xo;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),ll=function(){return o(function e(t,r,i){a(this,e),this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new ol(i),this.nonDisplayedMemory=new ol(i),this.lastOutputScreen=new ol(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i},[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,function(){return"MODE="+e}),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=this,r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);var i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return i+": "+t.writeScreen.getDisplayText(!0)}),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)}),this.outputDataUpdate())}},{key:"ccRCL",value:function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{key:"ccBS",value:function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{key:"ccAOF",value:function(){}},{key:"ccAON",value:function(){}},{key:"ccDER",value:function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{key:"ccRU",value:function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}},{key:"ccFON",value:function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}},{key:"ccRDC",value:function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{key:"ccTR",value:function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}},{key:"ccRTD",value:function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}},{key:"ccEDM",value:function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}},{key:"ccCR",value:function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}},{key:"ccENM",value:function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{key:"ccEOC",value:function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,function(){return"DISP: "+e.displayedMemory.getDisplayText()})}this.outputDataUpdate(!0)}},{key:"ccTO",value:function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}},{key:"ccMIDROW",value:function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+Kt(t)),this.writeScreen.setPen(t)}},{key:"outputDataUpdate",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}},{key:"cueSplitAtTime",value:function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}])}(),ul=function(){return o(function e(t,r,i){a(this,e),this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var n=this.logger=new rl;this.channels=[null,new ll(t,r,n),new ll(t+1,i,n)]},[{key:"getHandler",value:function(e){return this.channels[e].getHandler()}},{key:"setHandler",value:function(e,t){this.channels[e].setHandler(t)}},{key:"addData",value:function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,function(){return"["+il([t[e],t[e+1]])+"] -> ("+il([i,n])+")"});var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return cl(null,null,o),r.logger.log(3,function(){return"Repeated command ("+il([i,n])+") is dropped"}),0;cl(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else cl(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;if(l&&l>0)r.channels[l].insertChars(s);else r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,function(){return"Couldn't parse cleaned data "+il([i,n])+" orig: "+il([t[e],t[e+1]])})},n=0;n<t.length;n+=2)i(n)}},{key:"parseCmd",value:function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0}},{key:"parseMidrow",value:function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+il([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;r=t>=64&&t<=95?1===i?$o[e]:Zo[e]:1===i?Jo[e]:el[e];var n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0)}},{key:"interpretPAC",value:function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=!(1&~r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r,i,n=null,a=null;(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19)?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+zo(i)+"' in channel "+r}),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,function(){return"Char codes = "+il(n).join(",")}),n}},{key:"parseBackgroundAttributes",value:function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=tl[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(i),!0}},{key:"reset",value:function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}cl(null,null,this.cmdHistory)}},{key:"cueSplitAtTime",value:function(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}}}])}();function cl(e,t,r){r.a=e,r.b=t}var dl=function(){if(null!=di&&di.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var s in a)e[s]=a[s]}return e}function a(t,a,s){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var u="",c=!1,d=t,h=a,f=s,v=null,g="",p=!0,m="auto",y="start",E=50,k="middle",T=50,S="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return v},set:function(e){v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return g},set:function(t){var i=function(t){return r(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");g=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return k},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");k=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),hl=function(){return o(function e(){a(this,e)},[{key:"decode",value:function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}])}();function fl(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var vl=function(){return o(function e(){a(this,e),this.values=Object.create(null)},[{key:"set",value:function(e,t){this.get(e)||""===t||(this.values[e]=t)}},{key:"get",value:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}}},{key:"integer",value:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}},{key:"percent",value:function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}])}();function gl(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);if(2===s.length)t(s[0],s[1])}}var pl=new dl(0,0,""),ml="middle"===pl.align?"middle":"center";function yl(e,t,r){var i=e;function n(){var t=fl(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new vl;gl(e,function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",ml,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",ml,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",ml,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===pl.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",ml);var a=i.get("position","auto");"auto"===a&&50===pl.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function El(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var kl=function(){return o(function e(){a(this,e),this.state="INITIAL",this.buffer="",this.decoder=new hl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0},[{key:"parse",value:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=El(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),i}function i(e){gl(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var n="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var a=(n=r()).match(/^()?WEBVTT([ \t].*)?$/);if(null==a||!a[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:n=r(),t.state){case"HEADER":/:/.test(n)?i(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new dl(0,0,""),t.state="CUE",-1===n.indexOf("--\x3e")){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{yl(n,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var o=-1!==n.indexOf("--\x3e");if(!n||o&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=n;continue;case"BADCUE":n||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}},{key:"flush",value:function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}])}(),Tl=/\r\n|\n\r|\n|\r/g,Sl=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return e.slice(r,r+t.length)===t};function bl(e,t,r){return Po(e.toString())+Po(t.toString())+Po(r)}function Al(e,t,r,i,n,a,s){var o,l=new kl,u=be(new Uint8Array(e)).trim().replace(Tl,"\n").split("\n"),c=[],d=t?function(e){return Na(e,9e4,1/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1))}(t.baseTime,t.timescale):0,h="00:00.000",f=0,v=0,g=!0;l.oncue=function(e){var a=r[i],s=r.ccOffset,l=(f-d)/9e4;if(null!=a&&a.new&&(void 0!==v?s=r.ccOffset=a.start:function(e,t,r){var i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!=(a=n)&&a.new;){var a;e.ccOffset+=i.start-n.start,i.new=!1,n=e[(i=n).prevCC]}e.presentationOffset=r}(r,i,l)),l){if(!t)return void(o=new Error("Missing initPTS for VTT MPEGTS"));s=l-r.presentationOffset}var u=e.endTime-e.startTime,h=ja(9e4*(e.startTime+s-v),9e4*n)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+u,0);var g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=bl(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},l.onparsingerror=function(e){o=e},l.onflush=function(){o?s(o):a(c)},u.forEach(function(e){if(g){if(Sl(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach(function(e){Sl(e,"LOCAL:")?h=e.slice(6):Sl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{v=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(X(t)&&X(r)&&X(i)&&X(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*r,t+=6e4*i,t+36e5*n}(h)/1e3}catch(e){o=e}return}""===e&&(g=!1)}l.parse(e+"\n")}),l.flush()}var Ll="stpp.ttml.im1t",Il=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,wl={left:"start",center:"center",right:"end",start:"start",end:"end"};function Pl(e,t,r,i){var n=qe(new Uint8Array(e),["mdat"]);if(0!==n.length){var a=n.map(function(e){return be(e)}),s=function(e,t){return Na(e,t,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}(t.baseTime,1,t.timescale);try{a.forEach(function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce(function(e,t){return e[t]=i.getAttribute("ttp:".concat(t))||n[t],e},{}),s="preserve"!==i.getAttribute("xml:space"),o=Dl(xl(i,"styling","style")),l=Dl(xl(i,"layout","region")),u=xl(i,"body","[begin]");return[].map.call(u,function(e){var r=Cl(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=Ol(e.getAttribute("begin"),a),n=Ol(e.getAttribute("dur"),a),u=Ol(e.getAttribute("end"),a);if(null===i)throw Ml(e);if(null===u){if(null===n)throw Ml(e);u=i+n}var c=new dl(i-t,u-t,r);c.id=bl(c.startTime,c.endTime,c.text);var d=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;s&&r.hasOwnProperty(s)&&(n=r[s]);return a.reduce(function(r,a){var s=_l(t,i,a)||_l(e,i,a)||_l(n,i,a);return s&&(r[a]=s),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),h=d.textAlign;if(h){var f=wl[h];f&&(c.lineAlign=f),c.align=h}return de(c,d),c}).filter(function(e){return null!==e})}(e,s))})}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function xl(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Dl(e){return e.reduce(function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function Cl(e,t){return[].slice.call(e.childNodes).reduce(function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?Cl(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function _l(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Ml(e){return new Error("Could not parse ttml timestamp ".concat(e))}function Ol(e,t){if(!e)return null;var r=fl(e);return null===r&&(Il.test(e)?r=function(e,t){var r=Il.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):Rl.test(e)&&(r=function(e,t){var r=Rl.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}var Fl=function(){return o(function e(t,r){a(this,e),this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r},[{key:"dispatchCue",value:function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}},{key:"newCue",value:function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}},{key:"reset",value:function(){this.cueRanges=[],this.startTime=null}}])}(),Nl=function(){return o(function e(t){a(this,e),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ee.FRAG_LOADING,this.onFragLoading,this),t.on(ee.FRAG_LOADED,this.onFragLoaded,this),t.on(ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ee.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)},[{key:"destroy",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this),e.off(ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(ee.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}},{key:"initCea608Parsers",value:function(){var e=new Fl(this,"textTrack1"),t=new Fl(this,"textTrack2"),r=new Fl(this,"textTrack3"),i=new Fl(this,"textTrack4");this.cea608Parser1=new ul(1,e,t),this.cea608Parser2=new ul(3,r,i)}},{key:"addCues",value:function(e,t,r,i,n){for(var a=!1,s=n.length;s--;){var o=n[s],l=Gl(o[0],o[1],t,r);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),a=!0,l/(r-t)>.5))return}if(a||n.push([t,r]),this.config.renderTextTracksNatively){var u=this.captionsTracks[e];this.Cues.newCue(u,t,r,i)}else{var c=this.Cues.newCue(null,t,r,i);this.hls.trigger(ee.CUES_PARSED,{type:"captions",cues:c,track:e})}}},{key:"onInitPtsFound",value:function(e,t){var r=this,i=t.frag,n=t.id,a=t.initPTS,s=t.timescale,o=t.trackId,l=this.unparsedVttFrags;n===ae&&(this.initPTS[i.cc]={baseTime:a,timescale:s,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach(function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(ee.FRAG_LOADED,e):r.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}},{key:"getExistingTrack",value:function(e,t){var r=this.media;if(r)for(var i=0;i<r.textTracks.length;i++){var n=r.textTracks[i];if(Bl(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}},{key:"createCaptionsTrack",value:function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}},{key:"createNativeTrack",value:function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.media,n=t[e],a=n.label,s=n.languageCode,o=this.getExistingTrack(a,s);if(o)r[e]=o,Lo(r[e]),bo(r[e],i);else{var l=this.createTextTrack("captions",a,s);l&&(l[e]=!0,r[e]=l)}}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}}},{key:"createTextTrack",value:function(e,t,r){var i=this.media;if(i)return i.addTextTrack(e,t,r)}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){var i=this.captionsTracks;Object.keys(i).forEach(function(e){Lo(i[e]),delete i[e]}),this.nonNativeCaptionsTracks={}}}},{key:"onManifestLoading",value:function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{key:"_cleanTracks",value:function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var r=0;r<t.length;r++)Lo(t[r])}}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks||[],n=i.some(function(e){return e.textCodec===Ll});if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(os(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){var a=this.media,s=a?Ro(a.textTracks):null;if(this.tracks.forEach(function(e,t){var i;if(s){for(var n=null,a=0;a<s.length;a++)if(s[a]&&Bl(s[a],e)){n=s[a],s[a]=null;break}n&&(i=n)}if(i)Lo(i);else{var o=Ul(e);(i=r.createTextTrack(o,e.name,e.lang))&&(i.mode="disabled")}i&&r.textTracks.push(i)}),null!=s&&s.length){var o=s.filter(function(e){return null!==e}).map(function(e){return e.label});o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: ".concat(o.join(", "),". Replace media element for each source to clear TextTracks and captions menu."))}}else if(this.tracks.length){var l=this.tracks.map(function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}});this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}},{key:"onManifestLoaded",value:function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack".concat(t[1]),n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}})}},{key:"closedCaptionsForLevel",value:function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}},{key:"onFragLoading",value:function(e,t){if(this.enabled&&t.frag.type===ae){var r,i,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(r=null==(i=t.part)?void 0:i.index)?r:-1;n&&a&&(u!==s+1||u===s&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}},{key:"onFragLoaded",value:function(e,t){var r=t.frag,i=t.payload;if(r.type===oe)if(i.byteLength){var n=r.decryptdata,a="stats"in t;if(null==n||!n.encrypted||a){var s=this.tracks[r.level],o=this.vttCCs;o[r.cc]||(o[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),s&&s.textCodec===Ll?this._parseIMSC1(r,i):this._parseVTTs(t)}}else this.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}},{key:"_parseIMSC1",value:function(e,t){var r=this,i=this.hls;Pl(t,this.initPTS[e.cc],function(t){r._appendCues(t,e.level),i.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},function(t){i.logger.log("Failed to parse IMSC1: ".concat(t)),i.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}},{key:"_parseVTTs",value:function(e){var t,r=this,i=e.frag,n=e.payload,a=this.initPTS,s=this.unparsedVttFrags,o=a.length-1;if(a[i.cc]||-1!==o){var l=this.hls;Al(null!=(t=i.initSegment)&&t.data?it(i.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,function(e){r._appendCues(e,i.level),l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},function(t){var a="Missing initPTS for VTT MPEGTS"===t.message;a?s.push(e):r._fallbackToIMSC1(i,n),l.logger.log("Failed to parse VTT cue: ".concat(t)),a&&o>i.cc||l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}else s.push(e)}},{key:"_fallbackToIMSC1",value:function(e,t){var r=this,i=this.tracks[e.level];i.textCodec||Pl(t,this.initPTS[e.cc],function(){i.textCodec=Ll,r._parseIMSC1(e,t)},function(){i.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(function(e){return Ao(i,e)})}else{var n=this.tracks[t];if(!n)return;var a=n.default?"default":"subtitles"+t;r.trigger(ee.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}},{key:"onFragDecrypted",value:function(e,t){t.frag.type===oe&&this.onFragLoaded(ee.FRAG_LOADED,t)}},{key:"onSubtitleTracksCleared",value:function(){this.tracks=[],this.captionsTracks={}}},{key:"onFragParsingUserdata",value:function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,i=t.samples;if(r.type!==ae||"NONE"!==this.closedCaptionsForLevel(r))for(var n=0;n<i.length;n++){var a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,s[0]),this.cea608Parser2.addData(i[n].pts,s[1])}}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<i)){if(!a||"video"===a){var o=this.captionsTracks;Object.keys(o).forEach(function(e){return Io(o[e],r,i)})}if(this.config.renderTextTracksNatively&&0===r&&void 0!==n){var l=this.textTracks;Object.keys(l).forEach(function(e){return Io(l[e],r,n)})}}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],r=31&e[0],i=2,n=0;n<r;n++){var a=e[i++],s=127&e[i++],o=127&e[i++];if(0!==s||0!==o)if(!!(4&a)){var l=3&a;0!==l&&1!==l||(t[l].push(s),t[l].push(o))}}return t}}])}();function Ul(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Bl(e,t){return!!e&&e.kind===Ul(t)&&us(t,e)}function Gl(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}var Hl=/\s/,Vl={newCue:function(e,t,r,i){for(var n,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<i.rows.length;d++)if(s=!0,o=0,l="",!(n=i.rows[d]).isEmpty()){for(var h,f=0;f<n.chars.length;f++)Hl.test(n.chars[f].uchar)&&s?o++:(l+=n.chars[f].uchar,s=!1);n.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;var v=El(l.trim()),g=bl(t,r,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,r,v)).id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort(function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line}),u.forEach(function(t){return Ao(e,t)})),u}};var Kl=/(\d+)-(\d+)\/(\d+)/,jl=function(){return o(function e(t){a(this,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=t.fetchSetup||Yl,this.controller=new self.AbortController,this.stats=new xe},[{key:"destroy",value:function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}},{key:"abortInternal",value:function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}},{key:"load",value:function(e,t,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var a=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(de({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),s="arraybuffer"===e.responseType,o=s?"byteLength":"length",l=t.loadPolicy,u=l.maxTimeToFirstByteMs,c=l.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&X(u)?u:c,this.requestTimeout=self.setTimeout(function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))},t.timeout),(es(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(r){var a;i.response=i.loader=r;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(i.requestTimeout),t.timeout=c,i.requestTimeout=self.setTimeout(function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))},c-(o-n.loading.start)),!r.ok){var l=r.status,u=r.statusText;throw new Wl(u||"fetch, bad network response",l,r)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=Kl.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(X(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||n.total;var d=null==(a=i.callbacks)?void 0:a.onProgress;return d&&X(t.highWaterMark)?i.loadProgressively(r,n,e,t.highWaterMark,d):s?r.arrayBuffer():"json"===e.responseType?r.json():r.text()}).then(function(r){var a,s,l=i.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=r[o];u&&(n.loaded=n.total=u);var c={url:l.url,data:r,code:l.status},d=null==(a=i.callbacks)?void 0:a.onProgress;d&&!X(t.highWaterMark)&&d(n,e,r,l),null==(s=i.callbacks)||s.onSuccess(c,n,e,l)}).catch(function(t){var r;if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=t&&t.code||0,s=t?t.message:null;null==(r=i.callbacks)||r.onError({code:a,text:s},e,t?t.details:null,n)}})}},{key:"getCacheAge",value:function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.response?this.response.headers.get(e):null}},{key:"loadProgressively",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4?arguments[4]:void 0,a=new Ln,s=e.body.getReader(),o=function(){return s.read().then(function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<i||a.dataLength?(a.push(l),a.dataLength>=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}();function Yl(e,t){return new self.Request(e.url,t)}var Wl=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e])).code=void 0,s.details=void 0,s.code=r,s.details=i,s}return d(t,e),o(t)}(L(Error)),ql=/^age:\s*[\d.]+\s*$/im,zl=function(){return o(function e(t){a(this,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=t&&t.xhrSetup||null,this.stats=new xe,this.retryDelay=0},[{key:"destroy",value:function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}},{key:"abortInternal",value:function(){var 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()))}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}},{key:"load",value:function(e,t,r){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=r,this.loadInternal()}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then(function(){if(e.loader===i&&!e.stats.aborted)return a(i,r.url)}).catch(function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a(i,r.url)}).then(function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)}):this.openAndSendXhr(i,r,t)}}},{key:"openAndSendXhr",value:function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);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),r.timeout=a&&X(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=c,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var h={url:t.responseURL,data:o,code:a};return void(null==(u=this.callbacks)||u.onSuccess(h,r,e,t))}}var f,v=n.loadPolicy.errorRetry;if(cr(v,r.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else ke.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,r)}}}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(cr(e,this.stats.retry,!0))this.retry(e);else{var t;ke.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}}},{key:"retry",value:function(e){var t=this.context,r=this.stats;this.retryDelay=lr(e,r.retry),r.retry++,ke.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==t?void 0:t.url,", retrying ").concat(r.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}},{key:"loadprogress",value:function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}},{key:"getCacheAge",value:function(){var e=null;if(this.loader&&ql.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.loader&&new RegExp("^".concat(e,":\\s*[\\d.]+\\s*$"),"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}])}(),Xl=fe(fe({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:zl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Jt,bufferController:gs,capLevelController:ys,errorController:kr,fpsController:So,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:Ti,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},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:Vl,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:Yo,subtitleTrackController:wo,timelineController:Nl,audioStreamController:as,audioTrackController:cs,emeController:mo,cmcdController:fo,contentSteeringController:vo,interstitialsController:jo});function Ql(e){return e&&"object"===S(e)?Array.isArray(e)?e.map(Ql):Object.keys(e).reduce(function(t,r){return t[r]=Ql(e[r]),t},{}):e}function $l(e,t){var r=e.loader;r!==jl&&r!==zl?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=jl,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Jl=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["gap-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(ee.MEDIA_ENDED,{stalled:!1}))},i.hls=e,i.fragmentTracker=r,i.registerListeners(),i}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"destroy",value:function(){E(t,"destroy",this,3)([]),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}},{key:"onMediaAttached",value:function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;ln(r,"playing",this.onMediaPlaying),ln(r,"waiting",this.onMediaWaiting),ln(r,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var r=this.media;r&&(un(r,"playing",this.onMediaPlaying),un(r,"waiting",this.onMediaWaiting),un(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}},{key:"onBufferAppended",value:function(e,t){this.buffered=t.timeRanges}},{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}},{key:"tick",value:function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}}},{key:"poll",value:function(e,t){var r,i,n=null==(r=this.hls)?void 0:r.config;if(n){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(ee.MEDIA_ENDED,{stalled:!1})));if(jr.getBuffered(a).length){var c=jr.bufferInfo(a,e,0),d=c.nextStart||0,h=this.fragmentTracker;if(s&&h&&this.hls){var f=Zl(this.hls.inFlightFragments,e),v=c.len>2,g=!d||f||d-e>2&&!h.getPartialFragment(e);if(v||g)return;this.moved=!1}var p=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!d)return;var m=Math.max(d,c.start||0)-e,y=!(null==p||!p.live)?2*p.targetduration:2,E=tu(e,h);if(m>0&&(m<=y||E))return void(a.paused||this._trySkipBufferHole(E))}var k=n.detectStallWithCurrentTimeMs,T=self.performance.now(),S=this.waiting,b=this.stalled;if(null===b){if(!(S>0&&T-S<k))return void(this.stalled=T);b=this.stalled=S}var A=T-b;if(!s&&(A>=k||S)&&this.hls){var L;if("ended"===(null==(L=this.mediaSource)?void 0:L.readyState)&&(null==p||!p.live)&&Math.abs(e-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(ee.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}var I=jr.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(I,A,e)}else this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(r),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(ee.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=jr.bufferedInfo(jr.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=jr.timeRangesToArray(i),s=jr.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=jr.bufferedInfo(a,e,0).bufferedIndex,l=a[s].end,u=a[s+1].start;if((-1===o||o>s)&&u-l<1&&e-l<2){var c=new Error("nudging playhead to flush pipeline after video hole. currentTime: ".concat(e," hole: ").concat(l," -> ").concat(u," buffered index: ").concat(o));this.warn(c.message),this.media.currentTime+=1e-6;var d=tu(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var h=jr.bufferInfo(this.media,e,0);this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:d,buffer:h.len,bufferInfo:h})}}}}}},{key:"_tryFixBufferStall",value:function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=tu(r,a);if(u||null!=l&&l.live&&r<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}}},{key:"adjacentTraversal",value:function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,ae),a=r.getFragAtPos(i,ae);if(n&&a)return a.sn-n.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(r.currentTime," due to low buffer (").concat(Kt(e),")"));this.warn(a.message),t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}},{key:"_trySkipBufferHole",value:function(e){var t,r=this.fragmentTracker,i=this.media,n=null==(t=this.hls)?void 0:t.config;if(!i||!r||!n)return 0;var a=i.currentTime,s=jr.bufferInfo(i,a,0),o=a<s.start?s.start:s.nextStart;if(o&&this.hls){var l=s.len<=n.maxBufferHole,u=s.len>0&&s.len<1&&i.readyState<3,c=o-a;if(c>0&&(l||u)){if(c>n.maxBufferHole){var d=!1;if(0===a){var h=r.getAppendedFrag(0,ae);h&&o<h.end&&(d=!0)}if(!d&&e){var f;if(null==(f=this.hls.loadLevelObj)||!f.details)return 0;if(Zl(this.hls.inFlightFragments,o))return 0;for(var v=!1,g=e.end;g<o;){var p=tu(g,r);if(!p){v=!0;break}g+=p.duration}if(v)return 0}}var m=Math.max(o+.05,a+.1);if(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(m)),this.moved=!0,i.currentTime=m,null==e||!e.gap){var y=new Error("fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(m)),E={type:J.MEDIA_ERROR,details:Z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?E.part=e:E.frag=e),this.hls.trigger(ee.ERROR,E)}return m}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,n=null==t?void 0:t.config;if(!r||!n)return 0;var a=r.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){var s=a+(i+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),r.currentTime=s,t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @".concat(a," after ").concat(n.nudgeMaxRetry," nudges"));this.error(l.message),t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}])}(Hr);function Zl(e,t){var r=eu(e.main);if(r&&r.start<=t)return r;var i=eu(e.audio);return i&&i.start<=t?i:null}function eu(e){if(!e)return null;switch(e.state){case hn:case dn:case En:case kn:return null}return e.frag}function tu(e,t){return t.getAppendedFrag(e,ae)||t.getPartialFragment(e)}function ru(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function iu(e,t,r,i,n){var a=new e(t,r,"");try{a.value=i,n&&(a.type=n)}catch(s){a=new e(t,r,Kt(n?fe({type:n},i):i))}return a}var nu=function(){var e=ru();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),au=function(){return o(function e(t){var r=this;a(this,e),this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){r.hls&&r.hls.trigger(ee.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()},[{key:"destroy",value:function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}},{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"onMediaAttaching",value:function(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}},{key:"onMediaAttached",value:function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}},{key:"onMediaDetaching",value:function(e,t){this.media=null,!!t.transferMedia||(this.id3Track&&(this.removeCues&&Lo(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}},{key:"onManifestLoading",value:function(){this.dateRangeCuesAppended={}}},{key:"createTrack",value:function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t}},{key:"getID3Track",value:function(e){if(this.media){for(var t=0;t<e.length;t++){var r=e[t];if("metadata"===r.kind&&"id3"===r.label)return bo(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var r=this.hls.config,i=r.enableEmsgMetadataCues,n=r.enableID3MetadataCues;if(i||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=ru();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==Zn.emsg||i)&&n){var u=Xn(a[o].data),c=a[o].pts,d=c+a[o].duration;d>nu&&(d=nu),d-c<=0&&(d=c+.25);for(var h=0;h<u.length;h++){var f=u[h];if(!Qn(f)){this.updateId3CueEnds(c,l);var v=iu(s,c,d,f,l);v&&this.id3Track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(var n=i.length;n--;){var a=i[n];a.type===t&&a.startTime<e&&a.endTime===nu&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.type,a=this.id3Track,s=this.hls;if(s){var o=s.config,l=o.enableEmsgMetadataCues,u=o.enableID3MetadataCues;if(a&&(l||u))Io(a,r,i,"audio"===n?function(e){return e.type===Zn.audioId3&&u}:"video"===n?function(e){return e.type===Zn.emsg&&l}:function(e){return e.type===Zn.audioId3&&u||e.type===Zn.emsg&&l})}}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=ru();if(n&&a&&!o){var u=e.fragmentStart,c=e.fragmentEnd,d=this.assetCue;d?(d.startTime=u,d.endTime=c):l&&(d=this.assetCue=iu(l,u,c,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var h,f=this.id3Track,v=e.dateRanges,g=Object.keys(v),p=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.cues)&&h.length)for(var m,y=Object.keys(p).filter(function(e){return!g.includes(e)}),E=function(){var e=y[k],t=null==(m=p[e])?void 0:m.cues;delete p[e],t&&Object.keys(t).forEach(function(e){var i=t[e];if(i){i.removeEventListener("enter",r.onEventCueEnter);try{f.removeCue(i)}catch(e){}}})},k=y.length;k--;)E();else p=this.dateRangeCuesAppended={};var T=e.fragments[e.fragments.length-1];if(0!==g.length&&X(null==T?void 0:T.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=g[b],t=v[e],i=t.startTime,n=p[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=nu,c=t.duration;if(t.endDate&&null!==c)u=i+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,r){if(r!==t.id){var i=v[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var m=h[f];if(Zr(m)){var y=a[m];if(y)!s||null!=n&&n.durationKnown?Math.abs(y.startTime-i)>.01&&(y.startTime=i,y.endTime=u):y.endTime=u;else if(l){var E=t.attr[m];ei(m)&&(E=Le(E));var k=iu(l,i,u,{key:m,data:E},Zn.dateRange);k&&(k.id=e,r.id3Track.addCue(k),a[m]=k,o&&("X-ASSET-LIST"!==m&&"X-ASSET-URL"!==m||k.addEventListener("enter",r.onEventCueEnter)))}}}p[e]={cues:a,dateRange:t,durationKnown:s}},b=0;b<g.length;b++)S()}}}}}}])}(),su=function(){return o(function e(t){var r=this;a(this,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=function(){var e=r.media,t=r.levelDetails;if(e&&t){r.currentTime=e.currentTime;var i=r.computeLatency();if(null!==i){r._latency=i;var n=r.config,a=n.lowLatencyMode,s=n.maxLiveSyncPlaybackRate;if(a&&1!==s&&t.live){var o=r.targetLatency;if(null!==o){var l=i-o;if(l<Math.min(r.maxLatency,o+t.targetduration)&&l>.05&&r.forwardBufferLength>1){var u=Math.min(2,Math.max(1,s)),c=Math.round(2/(1+Math.exp(-.75*l-r.edgeStalled))*20)/20,d=Math.min(u,Math.max(1,c));r.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&r.changeMediaPlaybackRate(e,1)}}}}},this.hls=t,this.config=t.config,this.registerListeners()},[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var c=i;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.ERROR,this.onError,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.ERROR,this.onError,this))}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}},{key:"onManifestLoading",value:function(){this._latency=null,this.stallCount=0}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onError",value:function(e,t){var r;t.details===Z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(i=this.targetLatency)?void 0:i.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(e.playbackRate," to ").concat(t)),e.playbackRate=t)}},{key:"estimateLiveEdge",value:function(){var e=this.levelDetails;return null===e?null:e.edge+e.age}},{key:"computeLatency",value:function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}])}(),ou=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[e,"level-controller"]))._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}return d(t,e),o(t,[{key:"_registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.ERROR,this.onError,this)}},{key:"_unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.ERROR,this.onError,this)}},{key:"destroy",value:function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),E(t,"destroy",this,3)([])}},{key:"stopLoad",value:function(){this._levels.forEach(function(e){e.loadError=0,e.fragmentError=0}),E(t,"stopLoad",this,3)([])}},{key:"resetLevels",value:function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}},{key:"onManifestLoading",value:function(e,t){this.resetLevels()}},{key:"onManifestLoaded",value:function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1;t.levels.forEach(function(e){var t=e.attrs,c=e.audioCodec,d=e.videoCodec;c&&(e.audioCodec=c=Tt(c,i)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");i.length>2&&"avc1"===i[0]&&(t[r]="avc1.".concat(parseInt(i[1]).toString(16)).concat(("000"+parseInt(i[2]).toString(16)).slice(-4)))}return t.join(",")}(d));var h=e.width,f=e.height,v=e.unknownCodecs,g=(null==v?void 0:v.length)||0;if(o||(o=!(!h||!f)),l||(l=!!d),u||(u=!!c),g||c&&!r.isAudioSupported(c)||d&&!r.isVideoSupported(d))r.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'));else{var p=t.CODECS,m=t["FRAME-RATE"],y=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],k=t.RESOLUTION,T=t["VIDEO-RANGE"],S="".concat(E||".","-"),b="".concat(S).concat(e.bitrate,"-").concat(k,"-").concat(m,"-").concat(p,"-").concat(T,"-").concat(y);if(a[b])if(a[b].uri===e.url||e.attrs["PATHWAY-ID"])a[b].addGroupId("audio",t.AUDIO),a[b].addGroupId("text",t.SUBTITLES);else{var A=s[b]+=1;e.attrs["PATHWAY-ID"]=new Array(A+1).join(".");var L=r.createLevel(e);a[b]=L,n.push(L)}else{var I=r.createLevel(e);a[b]=I,s[b]=1,n.push(I)}}}),this.filterAndSortMediaOptions(n,t,o,l,u)}},{key:"createLevel",value:function(e){var t=new Gt(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(r.videoCodec,'"'));this.log(i.message),t.supportedResult=Pt(i,[])}return t}},{key:"isAudioSupported",value:function(e){return vt(e,"audio",this.hls.config.preferManagedMediaSource)}},{key:"isVideoSupported",value:function(e){return vt(e,"video",this.hls.config.preferManagedMediaSource)}},{key:"filterAndSortMediaOptions",value:function(e,t,r,i,n){var a,s=this,o=[],l=[],u=e,c=(null==(a=t.stats)?void 0:a.parsing)||{};if((r||i)&&n&&(u=u.filter(function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&(!!(t=i)&&Mt.indexOf(t)>-1)})),0===u.length)return Promise.resolve().then(function(){if(s.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: ".concat(Kt(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,r){return r.indexOf(e)===t}))),s.warn(r),e+=" (".concat(r,")"));var i=new Error(e);s.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}),void(c.end=performance.now());t.audioTracks&&lu(o=t.audioTracks.filter(function(e){return!e.audioCodec||s.isAudioSupported(e.audioCodec)})),t.subtitles&&lu(l=t.subtitles);var d=u.slice(0);u.sort(function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&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 Mt.indexOf(e.videoRange)-Mt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=mt(e.videoCodec),n=mt(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=yt(e.codecSet),s=yt(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});var h=d[0];if(this.steering&&(u=this.steering.filterParsedLevels(u)).length!==d.length)for(var f=0;f<d.length;f++)if(d[f].pathwayId===u[0].pathwayId){h=d[f];break}this._levels=u;for(var v=0;v<u.length;v++)if(u[v]===h){var g;this._firstLevel=v;var p=h.bitrate,m=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(u.length," level(s) found, first bitrate: ").concat(p)),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){var y=Math.min(p,this.hls.config.abrEwmaDefaultEstimateMax);y>m&&m===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var E=n&&!i,k=this.hls.config,T=!(!k.audioStreamController||!k.audioTrackController),S={levels:u,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:T&&!E&&o.some(function(e){return!!e.url})};c.end=performance.now(),this.hls.trigger(ee.MANIFEST_PARSED,S)}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level ".concat(e," (").concat(o.height?o.height+"p ":"").concat(o.videoRange?o.videoRange+" ":"").concat(o.codecSet?o.codecSet+" ":"","@").concat(o.bitrate,")").concat(l?" with Pathway "+l:""," from level ").concat(n).concat(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(ee.LEVEL_SWITCHING,u);var c=o.details;if(!c||c.live){var d=this.switchParams(o.uri,null==a?void 0:a.details,c);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter(function(e){return-1!==t.indexOf(e)});if(e.length<1)return void this.warn("pathwayPriority ".concat(e," should contain at least one pathway from list: ").concat(t));this.steering.pathwayPriority=r}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===re&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var r=t.frag;if(void 0!==r&&r.type===ae){var i=r.elementaryStreams;if(!Object.keys(i).some(function(e){return!!i[e]}))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of ".concat(n.loadError," on frag buffered")),n.loadError=0)}}},{key:"onLevelLoaded",value:function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(n)),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)}},{key:"loadPlaylist",value:function(e){E(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}},{key:"loadingPlaylist",value:function(e,r){E(t,"loadingPlaylist",this,3)([e,r]);var i=this.getUrlWithDirectives(e.uri,r),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],s=e.details,o=null==s?void 0:s.age;this.log("Loading level index ".concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(i)),this.hls.trigger(ee.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}},{key:"removeLevel",value:function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter(function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});Zi(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(ee.LEVELS_UPDATED,{levels:i})}}},{key:"onLevelsUpdated",value:function(e,t){var r=t.levels;this._levels=r}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(ee.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}])}(ss);function lu(e){var t={};e.forEach(function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}function uu(){return self.SourceBuffer||self.WebKitSourceBuffer}function cu(){if(!Te())return!1;var e=uu();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var du=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"stream-controller",ae])).audioCodecSwap=!1,s.level=-1,s._forceStartLoad=!1,s._hasEnoughToStart=!1,s.altAudio=0,s.audioOnly=!1,s.fragPlaying=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s.onMediaPlaying=function(){s.tick()},s.onMediaSeeked=function(){var e=s.media,t=e?e.currentTime:null;if(null!==t&&X(t)&&(s.log("Media seeked to ".concat(t.toFixed(3))),s.getBufferedFrag(t))){var r=s.getFwdBufferInfoAtPos(e,t,ae,0);null!==r&&0!==r.len?s.tick():s.warn("Main forward buffer length at ".concat(t,' on "seeked" event ').concat(r?r.len:"empty",")"))}},s.registerListeners(),s}return d(t,e),o(t,[{key:"registerListeners",value:function(){E(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){E(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"onHandlerDestroying",value:function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),E(t,"onHandlerDestroying",this,3)([])}},{key:"startLoad",value:function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=i.startLevel;-1===n&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r),this.state=hn,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=dn}},{key:"stopLoad",value:function(){this._forceStartLoad=!1,E(t,"stopLoad",this,3)([])}},{key:"doTick",value:function(){switch(this.state){case Sn:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=hn;break}if(this.hls.nextLoadLevel!==this.level){this.state=hn;break}break;case gn:this.checkRetryDate()}this.state===hn&&this.doTickIdle(),this.onTickEnd()}},{key:"onTickEnd",value:function(){var e;E(t,"onTickEnd",this,3)([]),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}},{key:"doTickIdle",value:function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(ee.BUFFER_EOS,l),void(this.state=En)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level ".concat(n," from level ").concat(this.level)),this.level=e.nextLoadLevel=n;var u=a.details;if(!u||this.state===Sn||this.waitForLive(a))return this.level=n,this.state=Sn,void(this.startFragRequested=!1);var c=s.len,d=this.getMaxBufferLength(a.maxBitrate);if(!(c>=d)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);var h=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&Oe(f)&&this.fragmentTracker.getState(f)!==Lr){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,p=u.fragments[g-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?De:Ce,y=(m===Ce?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,ae)}f=this.getNextFragmentLoopLoading(f,u,s,ae,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}}}}}}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n===Sr||n===Ar?Oe(e)?this.bitrateTest?(this.log("Fragment ".concat(e.sn," of level ").concat(e.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(e,r)):E(t,"loadFragment",this,3)([e,r,i]):this._loadInitSegment(e,r):this.clearTrackerIfNeeded(e)}},{key:"getBufferedFrag",value:function(e){return this.fragmentTracker.getBufferedFrag(e,ae)}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.end+.5):null}},{key:"immediateLevelSwitch",value:function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}},{key:"nextLevelSwitch",value:function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var a=this.getMainFwdBufferInfo();if(!a||a.len<2*n.targetduration)return}if(!t.paused&&e){var s=e[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);if(l){var u=this.followingBufferedFrag(l);if(u){this.abortCurrentFrag();var c=u.maxStartPTS?u.maxStartPTS:u.start,d=u.duration,h=Math.max(l.end,c+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}},{key:"abortCurrentFrag",value:function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case fn:case vn:case gn:case mn:case yn:this.state=hn}this.nextLoadPosition=this.getLoadPosition()}},{key:"flushMainBuffer",value:function(e,r){E(t,"flushMainBuffer",this,3)([e,r,2===this.altAudio?"video":null])}},{key:"onMediaAttached",value:function(e,r){E(t,"onMediaAttached",this,3)([e,r]);var i=r.media;ln(i,"playing",this.onMediaPlaying),ln(i,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,r){var i=this.media;i&&(un(i,"playing",this.onMediaPlaying),un(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,E(t,"onMediaDetaching",this,3)([e,r]),!!r.transferMedia||(this._hasEnoughToStart=!1)}},{key:"onManifestLoading",value:function(){E(t,"onManifestLoading",this,3)([]),this.log("Trigger BUFFER_RESET"),this.hls.trigger(ee.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}},{key:"onManifestParsed",value:function(e,t){for(var r,i,n=!1,a=!1,s=0;s<t.levels.length;s++){var o=t.levels[s].audioCodec;o&&(n=n||-1!==o.indexOf("mp4a.40.2"),a=a||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=n&&a&&!("function"==typeof(null==(i=uu())||null==(r=i.prototype)?void 0:r.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}},{key:"onLevelLoading",value:function(e,t){if(this.levels&&this.state===hn){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Sn)}}},{key:"onLevelLoaded",value:function(e,t){var r,i=this.levels,n=this.startFragRequested,a=t.level,s=t.details,o=s.totalduration;if(i){this.log("Level ".concat(a," loaded [").concat(s.startSN,",").concat(s.endSN,"]").concat(s.lastPartSn?"[part-".concat(s.lastPartSn,"-").concat(s.lastPartIndex,"]"):"",", cc [").concat(s.startCC,", ").concat(s.endCC,"] duration:").concat(o));var l=t.levelInfo,u=this.fragCurrent;!u||this.state!==vn&&this.state!==gn||u.level!==t.level&&u.loader&&this.abortCurrentFrag();var c=0;if(s.live||null!=(r=l.details)&&r.live){var d;if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;c=this.alignPlaylists(s,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=s,this.levelLastLoaded=l,n||this.setStartPosition(s,c),this.hls.trigger(ee.LEVEL_UPDATED,{details:s,level:a}),this.state===Sn){if(this.waitForCdnTuneIn(s))return;this.state=hn}n&&s.live&&this.synchronizeToLiveEdge(s),this.tick()}else this.warn("Levels were reset while loading level ".concat(a))}},{key:"synchronizeToLiveEdge",value:function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn("Playback: ".concat(n.toFixed(3)," is located too far from the end of live sliding playlist: ").concat(s,", reset currentTime to : ").concat(i.toFixed(3))),"buffered"===this.config.liveSyncMode){var u,c=jr.bufferInfo(r,i,0);if(null==(u=c.buffered)||!u.length)return void(r.currentTime=i);if(c.start<=n)return void(r.currentTime=i);var d=jr.bufferedInfo(c.buffered,n,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=i}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(r.sn," of level ").concat(r.level," after level details were reset")),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(s),h=this.transmuxer=this.transmuxer||new ns(this.hls,ae,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,v=-1!==f,g=new Vr(r.level,r.sn,r.stats.chunkCount,n.byteLength,f,v),p=this.initPTS[r.cc];h.push(n,c,d,l,r,i,o.totalduration,u,g,p)}else this.warn("Level ".concat(r.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var r=this,i=this.hls,n=2===this.altAudio;if($t(t.url,i))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;var a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.fragmentTracker.removeAllFragments(),i.once(ee.BUFFER_FLUSHED,function(){r.hls&&r.hls.trigger(ee.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(ee.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var r=$t(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?2:0,this.tick()}},{key:"onBufferCreated",value:function(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use ".concat(i,".buffered to schedule main fragment loading")),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=r.type===ae;if(n){if(this.fragContextChanged(r))return this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===yn&&(this.state=hn));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Oe(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}var s=this.media;s&&(!this._hasEnoughToStart&&jr.getBuffered(s).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"onError",value:function(e,t){var r;if(t.fatal)this.state=kn;else switch(t.details){case Z.FRAG_GAP:case Z.FRAG_PARSING_ERROR:case Z.FRAG_DECRYPT_ERROR:case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ae,t);break;case Z.LEVEL_LOAD_ERROR:case Z.LEVEL_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Sn||(null==(r=t.context)?void 0:r.type)!==re||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Z.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 Z.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=hn,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==De||!this.altAudio){var i=(r===Ce?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r,ae),this.tick())}}},{key:"onLevelsUpdated",value:function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"seekToStartPos",value:function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to ".concat(r,", already seeking at ").concat(t));var i=this.timelineOffset;i&&r&&(r+=i);var n=this.getLevelDetails(),a=jr.getBuffered(e),s=a.length?a.start(0):0,o=s-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log("adjusting start position by ".concat(o," to match buffer start")),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position ".concat(r," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=r)}}}},{key:"_getAudioCodec",value:function(e){var 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}},{key:"_loadBitrateTestFrag",value:function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var i=r.hls,n=null==e?void 0:e.frag;if(n&&!r.fragContextChanged(n)){t.fragmentError=0,r.state=hn,r.startFragRequested=!1,r.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(ee.FRAG_LOADED,e),n.bitrateTest=!1}}).catch(function(t){r.state!==dn&&r.state!==kn&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,r=this.hls,i=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=i.video,c=i.text,d=i.id3,h=i.initSegment,f=l.details,v=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=mn,h){var g=h.tracks;if(g){var p=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,p,n),r.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:t,tracks:g})}var m=h.initPTS,y=h.timescale,E=this.initPTS[s.cc];if(X(m)&&(!E||E.baseTime!==m||E.timescale!==y)){var k=h.trackId;this.initPTS[s.cc]={baseTime:m,timescale:y,trackId:k},r.trigger(ee.INIT_PTS_FOUND,{frag:s,id:t,initPTS:m,timescale:y,trackId:k})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var T=f.fragments[s.sn-1-f.startSN],S=s.sn===f.startSN,b=!T||s.cc>T.cc;if(!1!==i.independent){var A=u.startPTS,L=u.endPTS,I=u.startDTS,R=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:A,endPTS:L,startDTS:I,endDTS:R};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),P=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,x=u.firstKeyFramePTS?u.firstKeyFramePTS:A;if(!S&&P<x-this.config.maxBufferHole&&!b)return void this.backtrack(s);b&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,L,s.start,R,!0)}else S&&A-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,A,L,I,R),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,S||b)}else{if(!S&&!b)return void this.backtrack(s);s.gap=!0}}if(v){var D=v.startPTS,C=v.endPTS,_=v.startDTS,M=v.endDTS;o&&(o.elementaryStreams[De]={startPTS:D,endPTS:C,startDTS:_,endDTS:M}),s.setElementaryStreamInfo(De,D,C,_,M),this.bufferFragmentData(v,s,o,n)}if(f&&null!=d&&d.samples.length){var O={id:t,frag:s,details:f,samples:d.samples};r.trigger(ee.FRAG_PARSING_METADATA,O)}if(f&&c){var F={id:t,frag:s,details:f,samples:c.samples};r.trigger(ee.FRAG_PARSING_USERDATA,F)}}}else this.resetWhenMissingContext(n)}},{key:"logMuxedErr",value:function(e){this.warn("".concat(Oe(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}},{key:"_bufferInitSegment",value:function(e,t,r,i){var n=this;if(this.state===mn){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=St(a.codec,l);"mp4a"===u&&(u="mp4a.40.5");var c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=a.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&-1===c.indexOf("firefox")&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&-1!==c.indexOf("android")&&"audio/mpeg"!==a.container&&(u="mp4a.40.2",this.log("Android: force audio codec to ".concat(u))),l&&l!==u&&this.log('Swapping manifest audio codec "'.concat(l,'" for "').concat(u,'"')),a.levelCodec=u,a.id=ae,this.log("Init audio buffer, container:".concat(a.container,", codecs[selected/level/parsed]=[").concat(u||"","/").concat(l||"","/").concat(a.codec,"]")),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=ae;var h=s.codec;if(4===(null==h?void 0:h.length))switch(h){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:".concat(s.container,", codecs[level/parsed]=[").concat(e.videoCodec||"","/").concat(h,"]").concat(s.codec!==h?" parsed-corrected="+s.codec:"").concat(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:".concat(o.container,", codecs[level/parsed]=[").concat(e.codecs,"/").concat(o.codec,"]")),delete t.video,delete t.audio);var f=Object.keys(t);if(f.length){if(this.hls.trigger(ee.BUFFER_CODECS,t),!this.hls)return;f.forEach(function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(ee.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}}},{key:"getMainFwdBufferInfo",value:function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ae)}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"backtrack",value:function(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=hn}},{key:"checkFragmentChanged",value:function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(jr.isBuffered(e,r)?t=this.getAppendedFrag(r):jr.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,n=t.level;i&&t.sn===i.sn&&i.level===n||(this.fragPlaying=t,this.hls.trigger(ee.FRAG_CHANGED,{frag:t}),i&&i.level===n||this.hls.trigger(ee.LEVEL_SWITCHED,{level:n}))}}}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return X(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(X(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?er(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(bn),hu=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["key-loader",r])).config=void 0,i.keyIdToKeyInfo={},i.emeController=null,i.config=e,i}return d(t,e),o(t,[{key:"abort",value:function(e){for(var t in this.keyIdToKeyInfo){var r=this.keyIdToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}}},{key:"detach",value:function(){for(var e in this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}},{key:"destroy",value:function(){for(var e in this.detach(),this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}},{key:"createKeyLoadError",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.KEY_LOAD_ERROR,r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;return new Gr({type:J.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i})}},{key:"loadClear",value:function(e,t,r){var i=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(var n,a=function(){var n=t[s];if(e.cc<=n.cc&&(!Oe(e)||!Oe(n)||e.sn<n.sn)||!r&&s==o-1)return{v:i.emeController.selectKeySystemFormat(n).then(function(e){if(i.emeController){n.setKeyFormat(e);var t=mi(e);return t?i.emeController.getKeySystemAccess([t]):void 0}})}},s=0,o=t.length;s<o;s++)if(n=a())return n.v;if(this.config.requireKeySystemAccessOnStart){var l=Ei(this.config);if(l.length)return this.emeController.getKeySystemAccess(l)}}return null}},{key:"load",value:function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(function(r){return t.loadInternal(e,r)}):this.loadInternal(e)}},{key:"loadInternal",value:function(e,t){var r,i;t&&e.setKeyFormat(t);var n=e.decryptdata;if(!n){var a=new Error(t?"Expected frag.decryptdata to be defined after setting format ".concat(t):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,a))}var s=n.uri;if(!s)return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(s,'"'))));var o=fu(n),l=this.keyIdToKeyInfo[o];if(null!=(r=l)&&r.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(i=l)&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(function(t){var r=t.keyInfo;return n.key=r.decryptdata.key,{frag:e,keyInfo:r}})}switch(this.log("".concat(this.keyIdToKeyInfo[o]?"Rel":"L","oading").concat(n.keyId?" keyId: "+Ae(n.keyId):""," URI: ").concat(n.uri," from ").concat(e.type," ").concat(e.level)),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(n.method,'"'))))}}},{key:"loadKeyEME",value:function(e,t){var r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){var n=function(e){var t=[];return tt(e,function(e){return t.push(e.subarray(8,24))}),t}(t.initSegment.data);if(n.length){var a=n[0];a.some(function(e){return 0!==e})&&(this.log("Using keyId found in init segment ".concat(Ae(a))),e.decryptdata.keyId=a,Ai.setKeyIdForUri(e.decryptdata.uri,a))}}var s=this.emeController.loadKey(r);return(e.keyLoadPromise=s.then(function(t){return e.mediaKeySessionContext=t,r})).catch(function(r){throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(r)}},{key:"loadKeyHTTP",value:function(e,t){var r=this,i=this.config,n=new(0,i.loader)(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise(function(a,s){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:function(e,t,i,n){var o=i.frag,l=i.keyInfo,u=fu(l.decryptdata);if(!o.decryptdata||l!==r.keyIdToKeyInfo[u])return s(r.createKeyLoadError(o,Z.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,a({frag:o,keyInfo:l})},onError:function(e,i,n,a){r.resetLoader(i),s(r.createKeyLoadError(t,Z.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(e.code," loading key ").concat(e.text)),n,fe({url:o.url,data:void 0},e)))},onTimeout:function(e,i,n){r.resetLoader(i),s(r.createKeyLoadError(t,Z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:function(e,i,n){r.resetLoader(i),s(r.createKeyLoadError(t,Z.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(o,u,c)})}},{key:"resetLoader",value:function(e){var t=e.frag,r=e.keyInfo,i=e.url,n=r.loader;t.keyLoader===n&&(t.keyLoader=null,r.loader=null);var a=fu(r.decryptdata)||i;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}])}(ve);function fu(e){if(e.keyFormat!==vi){var t=e.keyId;if(t)return Ae(t)}return e.uri}function vu(e){switch(e.type){case ie:return se;case ne:return oe;default:return ae}}function gu(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var pu=function(){return o(function e(t){a(this,e),this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()},[{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.destroyInternalLoaders()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"createInternalLoader",value:function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n}},{key:"getInternalLoader",value:function(e){return this.loaders[e.type]}},{key:"resetInternalLoader",value:function(e){this.loaders[e]&&delete this.loaders[e]}},{key:"destroyInternalLoaders",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}},{key:"destroy",value:function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}},{key:"onManifestLoading",value:function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te,url:r,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var r=t.id,i=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:re,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ie,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ne,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var r=this.loaders[re];if(r){var i=r.context;i&&!t.levels.some(function(e){return e===i.levelOrTrack})&&(r.abort(),delete this.loaders[re])}}},{key:"load",value:function(e){var t,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,l=s.context;if(l&&l.levelOrTrack===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives))return void(l.url===e.url?o.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):o.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(l.url)));o.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),s.abort()}if((r=e.type===te?a.manifestLoadPolicy.default:de({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),X(null==(t=e.deliveryDirectives)?void 0:t.part))&&(e.type===re&&null!==e.level?i=this.hls.levels[e.level].details:e.type===ie&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===ne&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,c=i.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);r=de({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var h=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),Di.isMediaPlaylist(s)||r.type!==te?n.handleTrackOrLevelPlaylist(e,t,r,i||null,a):n.handleMasterPlaylist(e,t,r,i)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,n=e.forceStartLoad;(r||n)&&(this.hls.logger.log("".concat(r?"auto":"force"," startLoad with configured startPosition ").concat(i)),this.hls.startLoad(i))}}},{key:"handleMasterPlaylist",value:function(e,t,r,i){var n=this,a=this.hls,s=e.data,o=gu(e,r),l=Di.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,i,t);var u=l.contentSteering,c=l.levels,d=l.sessionData,h=l.sessionKeys,f=l.startTimeOffset,v=l.variableList;this.variableList=v,c.forEach(function(e){var t=e.unknownCodecs;if(t)for(var r=n.hls.config.preferManagedMediaSource,i=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];vt(o,"audio",r)?(e.audioCodec=i=i?"".concat(i,",").concat(o):o,ht.audio[i.substring(0,4)]=2,t.splice(s,1)):vt(o,"video",r)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,ht.video[a.substring(0,4)]=2,t.splice(s,1))}});var g=Di.parseMasterPlaylistMedia(s,o,l),p=g.AUDIO,m=void 0===p?[]:p,y=g.SUBTITLES,E=g["CLOSED-CAPTIONS"];m.length&&(m.some(function(e){return!e.url})||!c[0].audioCodec||c[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Jr({}),bitrate:0,url:""})));a.trigger(ee.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:y,captions:E,contentSteering:u,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:v})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=gu(e,r),c=X(o)?o:X(s)?s:0,d=vu(r),h=Di.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===te){var f={attrs:new Jr({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Xi(h,0),a.trigger(ee.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,i,n)}},{key:"handleManifestParsingError",value:function(e,t,r,i,n){this.hls.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.MANIFEST_PARSING_ERROR,fatal:t.type===te,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})}},{key:"handleNetworkError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,a="A network ".concat(r?"timeout":"error"+(i?" (status "+i.code+")":"")," occurred while loading ").concat(e.type);e.type===re?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==ie&&e.type!==ne||(a+=" id: ".concat(e.id,' group-id: "').concat(e.groupId,'"'));var s=new Error(a);this.hls.logger.warn("[playlist-loader]: ".concat(a));var o=Z.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case te:o=r?Z.MANIFEST_LOAD_TIMEOUT:Z.MANIFEST_LOAD_ERROR,l=!0;break;case re:o=r?Z.LEVEL_LOAD_TIMEOUT:Z.LEVEL_LOAD_ERROR,l=!1;break;case ie:o=r?Z.AUDIO_TRACK_LOAD_TIMEOUT:Z.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ne:o=r?Z.SUBTITLE_TRACK_LOAD_TIMEOUT:Z.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:J.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:n};if(i){var d=(null==t?void 0:t.url)||e.url;c.response=fe({url:d,data:void 0},i)}this.hls.trigger(ee.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.levelOrTrack,c=i.id,d=i.groupId,h=i.deliveryDirectives,f=gu(t,i),v=vu(i),g="number"==typeof i.level&&v===ae?l:void 0,p=e.playlistParsingError;if(p){if(this.hls.logger.warn("".concat(p," ").concat(e.url)),!s.config.ignorePlaylistParsingErrors)return void s.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case te:case re:if(g)if(u){if(u!==s.levels[g]){var m=s.levels.indexOf(u);m>-1&&(g=m)}}else g=0;s.trigger(ee.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:r,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:o===te});break;case ie:s.trigger(ee.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h});break;case ne:s.trigger(ee.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r})}}}])}(),mu=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,e),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Pn,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;var r=this.logger=function(e,t,r){var i=me();if("object"===("undefined"==typeof console?"undefined":S(console))&&!0===e||"object"===S(e)){var n=["debug","log","info","warn","error"];n.forEach(function(t){i[t]=ye(t,e,r)});try{i.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.6.14"))}catch(e){return me()}n.forEach(function(t){Ee[t]=ye(t,e)})}else de(Ee,i);return i}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(e,t,r){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"');var i=Ql(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(function(e){var a="".concat("level"===e?"playlist":e,"LoadPolicy"),s=void 0===t[a],o=[];n.forEach(function(r){var n="".concat(e,"Loading").concat(r),l=t[n];if(void 0!==l&&s){o.push(n);var u=i[a].default;switch(t[a]={default:u},r){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn('hls.js config: "'.concat(o.join('", "'),'" setting(s) are deprecated, use "').concat(a,'": ').concat(Kt(t[a])))}),fe(fe({},i),t)}(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&$l(i,r);var n=i.abrController,s=i.bufferController,o=i.capLevelController,l=i.errorController,u=i.fpsController,c=new l(this),d=this.abrController=new n(this),h=new Ir(this),f=i.interstitialsController,v=f?this.interstitialsController=new f(this,e):null,g=this.bufferController=new s(this,h),p=this.capLevelController=new o(this),m=new u(this),y=new pu(this),E=i.contentSteeringController,k=E?new E(this):null,T=this.levelController=new ou(this,k),b=new au(this),A=new hu(this.config,this.logger),L=this.streamController=new du(this,h,A),I=this.gapController=new Jl(this,h);p.setStreamController(L),m.setStreamController(L);var R=[y,T,L];v&&R.splice(1,0,v),k&&R.splice(1,0,k),this.networkControllers=R;var w=[d,g,I,p,m,b,h];this.audioTrackController=this.createController(i.audioTrackController,R);var P=i.audioStreamController;P&&R.push(this.audioStreamController=new P(this,h,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);var x=i.subtitleStreamController;x&&R.push(this.subtititleStreamController=new x(this,h,A)),this.createController(i.timelineController,w),A.emeController=this.emeController=this.createController(i.emeController,w),this.cmcdController=this.createController(i.cmcdController,w),this.latencyController=this.createController(su,w),this.coreComponents=w,R.push(c);var D=c.onErrorOut;"function"==typeof D&&this.on(ee.ERROR,D,c),this.on(ee.MANIFEST_LOADED,y.onManifestLoaded,y)}return o(e,[{key:"createController",value:function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,r)}},{key:"once",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,r)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,i=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,r,i)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,r){return this._emitter.emit(e,t,r)}},{key:"trigger",value:function(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;var r=e===ee.ERROR;this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1}},{key:"listenerCount",value:function(e){return this._emitter.listenerCount(e)}},{key:"destroy",value:function(){this.logger.log("destroy"),this.trigger(ee.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(function(e){return e.destroy()}),this.networkControllers.length=0,this.coreComponents.forEach(function(e){return e.destroy()}),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}},{key:"attachMedia",value:function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument (".concat(e,")"));this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(ee.MEDIA_ATTACHING,n)}}},{key:"detachMedia",value:function(){this.logger.log("detachMedia"),this.trigger(ee.MEDIA_DETACHING,{}),this._media=null}},{key:"transferMedia",value:function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(ee.MEDIA_DETACHING,{transferMedia:e}),e}},{key:"loadSource",value:function(e){this.stopLoad();var t=this.media,r=this._url,i=this._url=Pe.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(i)),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(ee.MANIFEST_LOADING,{url:e})}},{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,t=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}},{key:"stopLoad",value:function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"resumeBuffering",value:function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(function(e){e.resumeBuffering&&e.resumeBuffering()}))}},{key:"pauseBuffering",value:function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(function(e){e.pauseBuffering&&e.pauseBuffering()}))}},{key:"inFlightFragments",get:function(){var e=l({},ae,this.streamController.inFlightFrag);return this.audioStreamController&&(e[se]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[oe]=this.subtititleStreamController.inFlightFrag),e}},{key:"swapAudioCodec",value:function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}},{key:"removeLevel",value:function(e){this.levelController.removeLevel(e)}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})}}}()),e}},{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:".concat(e)),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:".concat(e)),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:".concat(e)),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:".concat(e)),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return _t.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"setAudioOption",value:function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}},{key:"setSubtitleOption",value:function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(e){this.latencyController.targetLatency=e}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}},{key:"getMediaDecodingInfo",value:function(e){return xt(e,Yt(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return xn}},{key:"isMSESupported",value:function(){return cu()}},{key:"isSupported",value:function(){return function(){if(!cu())return!1;var e=Te();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(function(t){return e.isTypeSupported(pt(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(pt(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return Te()}},{key:"Events",get:function(){return ee}},{key:"MetadataSchema",get:function(){return Zn}},{key:"ErrorTypes",get:function(){return J}},{key:"ErrorDetails",get:function(){return Z}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:Xl},set:function(t){e.defaultConfig=t}}])}();mu.defaultConfig=void 0;var yu=[".mp4",".webm",".ogg",".m3u8",".ts"],Eu=[".flv",".f4v",".swf",".wmv",".avi",".mov",".mkv"];function ku(e){try{var t=new URL(e,"http://dummy").pathname;return-1===(r=t.lastIndexOf("."))?"":t.slice(r).toLowerCase()}catch(t){var r;return-1===(r=e.lastIndexOf("."))?"":(e.slice(r).split(/[?#]/)[0]||"").toLowerCase()}}function Tu(e){var t=ku(e);return-1!==Eu.indexOf(t)}function Su(e,t){var r,i,n,a=t.licenseKey,s=t.debug,o=void 0!==s&&s,l=!1,u=!1,c=Math.max(0,Math.min(1,e.volume||1)),d=new Map,h={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function f(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];o&&console.log.apply(console,M(["[AdStormPlayer]"],_(e),!1))}function v(e,t){var r,i,n=d.get(e);if(n)try{for(var a=C(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("[AdStormPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function g(e){e&&0!==e.length&&e.forEach(function(e){try{new Image(1,1).src=e,f("Fired tracking pixel:",e)}catch(e){console.warn("[AdStormPlayer] Error firing tracking pixel:",e)}})}function p(e){var t=[];try{var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.querySelector("parsererror");if(i)return console.error("[AdStormPlayer] XML parsing error:",i.textContent),[];r.querySelectorAll("Ad").forEach(function(e){var r,i,n,a,s=e.getAttribute("id")||"unknown",o=(null===(r=e.querySelector("AdTitle"))||void 0===r?void 0:r.textContent)||"Ad",l=((null===(i=e.querySelector("Duration"))||void 0===i?void 0:i.textContent)||"00:00:30").split(":"),u=3600*parseInt(l[0]||"0",10)+60*parseInt(l[1]||"0",10)+parseFloat(l[2]||"0"),c=e.querySelectorAll("MediaFile"),d=[];if(c.forEach(function(e){var t,r=e.getAttribute("type")||"",i=(null===(t=e.textContent)||void 0===t?void 0:t.trim())||"",n=parseInt(e.getAttribute("width")||"1920",10),a=parseInt(e.getAttribute("height")||"1080",10),s=e.getAttribute("bitrate")?parseInt(e.getAttribute("bitrate"),10):void 0;if(i){var o=i;if((i=function(e){return".flv"===ku(e)?e.replace(/\.flv(\?|$)/i,".mp4$1"):e}(i))!==o&&f("Converted FLV to MP4: ".concat(o," -> ").concat(i)),Tu(i)){var l=ku(i);f("Skipping unsupported format: ".concat(i," (extension: ").concat(l,", declared type: ").concat(r,")"))}else!function(e,t){if(Tu(e))return!1;var r=ku(e);return-1!==yu.indexOf(r)||(""===r||"."===r)&&(t.includes("video/mp4")||t.includes("video/webm")||t.includes("m3u8")||t.includes("application/x-mpegurl"))}(i,r)?f("Skipping incompatible media file: ".concat(i," (type: ").concat(r,")")):(d.push({url:i,type:r,width:n,height:a,bitrate:s}),f("Found media file: ".concat(i," (").concat(r,", ").concat(n,"x").concat(a,")")))}else f("Skipping empty MediaFile URL")}),0!==d.length){var h={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],error:[]};e.querySelectorAll("Impression").forEach(function(e){var t,r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&h.impression.push(r)}),e.querySelectorAll("Tracking").forEach(function(e){var t,r=e.getAttribute("event"),i=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(r&&i){var n=r;h[n]&&h[n].push(i)}});var v=null===(a=null===(n=e.querySelector("ClickThrough"))||void 0===n?void 0:n.textContent)||void 0===a?void 0:a.trim();t.push({id:s,title:o,duration:u,mediaFiles:d,trackingUrls:h,clickThrough:v}),f("Parsed ad: ".concat(o,", duration: ").concat(u,"s, media files: ").concat(d.length))}else f("No valid media files found in ad:",s)})}catch(e){console.error("[AdStormPlayer] Error parsing VAST XML:",e)}return t}function m(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function y(){if(r&&n){var t=n;r.addEventListener("timeupdate",function(){if(t&&r){var e=r.currentTime/t.duration;e>=.25&&!h.firstQuartile&&(h.firstQuartile=!0,g(t.trackingUrls.firstQuartile)),e>=.5&&!h.midpoint&&(h.midpoint=!0,g(t.trackingUrls.midpoint)),e>=.75&&!h.thirdQuartile&&(h.thirdQuartile=!0,g(t.trackingUrls.thirdQuartile))}}),r.addEventListener("playing",function(){t&&!h.start&&(h.start=!0,g(t.trackingUrls.start),f("Ad started playing"))}),r.addEventListener("ended",function(){t&&!h.complete&&(h.complete=!0,g(t.trackingUrls.complete),f("Ad completed"),function(){f("Handling ad completion"),l=!1,m(!1),i&&(i.style.opacity="0",setTimeout(function(){i&&(i.style.display="none",i.style.pointerEvents="none")},300));e.style.visibility="visible",e.style.opacity="1",e.muted=u,e.volume=c,v("content_resume"),v("all_ads_completed")}())}),r.addEventListener("error",function(e){console.error("[AdStormPlayer] Ad video error:",e),t&&g(t.trackingUrls.error),E()})}}function E(){f("Handling ad error"),l=!1,m(!1),e.muted=u,e.volume=c,e.style.visibility="visible",e.style.opacity="1",i&&(i.style.display="none",i.style.pointerEvents="none"),v("ad_error")}function k(t){return x(this,void 0,void 0,function(){var r,i,n;return D(this,function(s){switch(s.label){case 0:return r=function(t,r){var i="https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(a,"/pod"),n={video:{codec:"h264",width:e.videoWidth||1280,height:e.videoHeight||720,fps:29.97,bitrate:5e3,profile:"high",pix_fmt:"yuv420p",has_b_frames:0},audio:{codec:"aac",sample_rate:48e3,bitrate:128}},s=r||n,o=encodeURIComponent(JSON.stringify(s));return"".concat(i,"?duration=").concat(Math.ceil(t),"&metadata=").concat(o)}(t),f("Fetching VAST from:",r),[4,fetch(r,{headers:{Accept:"application/xml"}})];case 1:if(!(i=s.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(i.status," ").concat(i.statusText));return[4,i.text()];case 2:return f("VAST response received, length:",(n=s.sent()).length),[2,p(n)]}})})}return{initialize:function(){var t;if(f("Initializing"),!i){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",r.style.transition="opacity 0.3s ease-in-out",r.style.opacity="0",null===(t=e.parentElement)||void 0===t||t.appendChild(r),i=r}},requestAds:function(e){return x(this,void 0,void 0,function(){var t,r,i,a;return D(this,function(s){switch(s.label){case 0:if(f("Requesting ads for duration:",e),l)return[2,Promise.reject(new Error("Ad already playing"))];s.label=1;case 1:return s.trys.push([1,3,,4]),t=30,r=parseInt(e,10),!isNaN(r)&&r>0&&(t=r),[4,k(t)];case 2:return 0===(i=s.sent()).length?(f("No ads available from VAST response"),v("ad_error"),[2,Promise.resolve()]):(n=i[0],f("Ad loaded: ".concat(n.title,", duration: ").concat(n.duration,"s")),g(n.trackingUrls.impression),h.impression=!0,[2,Promise.resolve()]);case 3:return a=s.sent(),console.error("[AdStormPlayer] Error requesting ads:",a),v("ad_error"),[2,Promise.reject(a)];case 4:return[2]}})})},play:function(){return x(this,void 0,void 0,function(){var t,a;return D(this,function(s){switch(s.label){case 0:if(!n)return[2,Promise.reject(new Error("No ad loaded"))];f("Starting ad playback"),s.label=1;case 1:if(s.trys.push([1,3,,4]),r||((o=document.createElement("video")).style.position="absolute",o.style.left="0",o.style.top="0",o.style.width="100%",o.style.height="100%",o.style.objectFit="contain",o.style.backgroundColor="#000",o.style.zIndex="15",o.playsInline=!0,o.muted=!1,o.volume=u?0:c,r=o,null==i||i.appendChild(r),y()),h={impression:h.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",setTimeout(function(){e.style.visibility="hidden"},300),e.muted=!0,e.volume=0,e.pause(),l=!0,m(!0),r&&(r.volume=u?0:c,r.muted=u),i&&(i.style.display="flex",i.style.pointerEvents="auto",i.offsetHeight,i.style.opacity="1"),v("content_pause"),!(t=function(t){if(0===t.length)return null;if(1===t.length)return t[0];var r=t.filter(function(e){return e.type.includes("video/mp4")}),i=r.length>0?r:t,n=e.videoWidth||1280,a=e.videoHeight||720;return i.sort(function(e,t){return Math.abs(e.width-n)+Math.abs(e.height-a)-(Math.abs(t.width-n)+Math.abs(t.height-a))}),i[0]||null}(n.mediaFiles)))throw new Error("No media file available");return f("Playing media file:",t.url),r.src=t.url,[4,r.play()];case 2:return s.sent(),[2,Promise.resolve()];case 3:return a=s.sent(),console.error("[AdStormPlayer] Error playing ad:",a),E(),[2,Promise.reject(a)];case 4:return[2]}var o})})},stop:function(){return x(this,void 0,void 0,function(){return D(this,function(t){return f("Stopping ad"),l=!1,m(!1),i&&(i.style.opacity="0",setTimeout(function(){i&&(i.style.display="none",i.style.pointerEvents="none")},300)),r&&(r.pause(),r.src=""),e.style.visibility="visible",e.style.opacity="1",n=void 0,[2]})})},destroy:function(){f("Destroying"),l=!1,m(!1),e.muted=u,e.volume=c,e.style.visibility="visible",e.style.opacity="1",r&&(r.pause(),r.src="",r.remove(),r=void 0),(null==i?void 0:i.parentElement)&&i.parentElement.removeChild(i),i=void 0,n=void 0,d.clear()},isAdPlaying:function(){return l},resize:function(e,t){f("Resizing to ".concat(e,"x").concat(t)),i&&(i.style.width="".concat(e,"px"),i.style.height="".concat(t,"px")),r&&(r.style.width="".concat(e,"px"),r.style.height="".concat(t,"px"))},on:function(e,t){d.has(e)||d.set(e,new Set),d.get(e).add(t)},off:function(e,t){var r;null===(r=d.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?c:Math.max(0,Math.min(1,t));f("updateOriginalMutedState: muted=".concat(e,", volume=").concat(r)),u=e,c=r},getOriginalMutedState:function(){return u},getOriginalVolume:function(){return c},setAdVolume:function(e){r&&l&&(r.volume=Math.max(0,Math.min(1,e)),r.muted=0===e)},getAdVolume:function(){return r&&l?r.volume:1},showPlaceholder:function(){var t;if(!i){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),i=r}i&&(i.style.display="flex",i.style.opacity="1",i.style.pointerEvents="auto")},hidePlaceholder:function(){i&&(i.style.opacity="0",setTimeout(function(){i&&(i.style.display="none",i.style.pointerEvents="none")},300))}}}function bu(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=0;n<t.length;n++){var a=t[n];if(null!=a)for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(i[s]=a[s])}return i}),Array.from||(Array.from=function(e,t,r){var i=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var n=i.length>>>0,a=new Array(n),s=0;s<n;s++)a[s]=t?t.call(r,i[s],s):i[s];return a}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){var e=function(){function e(t){var r=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){r.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,r=e.startsWith("?")?e.slice(1):e;r&&r.split("&").forEach(function(e){var r=_(e.split("="),2),i=r[0],n=r[1];if(i){var a=t.safeDecodeURIComponent(i),s=n?t.safeDecodeURIComponent(n):"";t.append(a,s)}})},e.prototype.safeDecodeURIComponent=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},e.prototype.append=function(e,t){var r=this.params.get(e)||[];r.push(String(t)),this.params.set(e,r)},e.prototype.delete=function(e){this.params.delete(e)},e.prototype.get=function(e){var t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null},e.prototype.getAll=function(e){return this.params.get(e)||[]},e.prototype.has=function(e){return this.params.has(e)},e.prototype.set=function(e,t){this.params.set(e,[String(t)])},e.prototype.forEach=function(e){var t=this;this.params.forEach(function(r,i){r.forEach(function(r){e(r,i,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,r){t.forEach(function(t){e.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(t)))})}),e.join("&")},e}();window.URLSearchParams=e}}(),function(){if("undefined"==typeof TextEncoder){var e=function(){function e(){this.encoding="utf-8"}return e.prototype.encode=function(e){for(var t=[],r=0;r<e.length;r++){var i=e.charCodeAt(r);i<128?t.push(i):i<2048?t.push(192|i>>6,128|63&i):i<55296||i>=57344?t.push(224|i>>12,128|i>>6&63,128|63&i):(r++,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i))}return new Uint8Array(t)},e}();window.TextEncoder=e}}(),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){var t=this.constructor;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})})}function Au(){var e=navigator.userAgent,t=function(){var e;if("userAgentData"in navigator&&(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform))return navigator.userAgentData.platform;var t=navigator.userAgent;return/Mac|iPhone|iPad|iPod/i.test(t)?/iPhone|iPad|iPod/i.test(t)?"iPhone":"MacIntel":/Win/i.test(t)?"Win32":/Linux/i.test(t)?/Android/i.test(t)?"Linux armv8l":"Linux x86_64":/CrOS/i.test(t)?"CrOS":navigator.platform||"Unknown"}(),r="Unknown",i="0",n=0,a=!1,s=!1,o=!0;if(/Web0S|webOS/i.test(e))r="LG WebOS",a=!0,"Unknown"!==(i=(l=e.match(/Web0S[/\s]*([\d.]+)/i))&&l[1]?l[1]:"Unknown")&&(n=(u=i.split("."))[0]?parseInt(u[0],10):0);else if(/Tizen/i.test(e)){var l,u;if(r="Samsung Tizen",a=!0,"Unknown"!==(i=(l=e.match(/Tizen[/\s]*([\d.]+)/i))&&l[1]?l[1]:"Unknown"))n=(u=i.split("."))[0]?parseInt(u[0],10):0}else/SMART-TV|SmartTV/i.test(e)?(r="Smart TV",a=!0):/NetCast/i.test(e)?(r="LG NetCast",a=!0,s=!0):/BRAVIA/i.test(e)&&(r="Sony BRAVIA",a=!0);var c=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e),d=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e);return c>0&&(a||(r="Chrome",i=c.toString(),n=c),c<50&&(o=!1,s=!0)),d>0&&d<600&&(o=!1,a&&(s=!0)),"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(o=!1),"undefined"==typeof URLSearchParams&&(o=!1),{name:r,version:i,majorVersion:n,isSmartTV:a,isLegacyTV:s,platform:t,supportsModernJS:o}}function Lu(e){if(void 0===e&&(e=!1),e){var t=Au();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",{browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsModernJS:t.supportsModernJS,userAgent:navigator.userAgent})}}function Iu(){var e={};return Au().isSmartTV&&(e.allowNativeHls=!0),e}var Ru=function(){function e(e){var t;this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,bu();var r=Iu();this.config=w(w({},e),r),this.video=e.videoElement,Lu(e.debugAdTiming),this.config.licenseKey||console.warn("[StormcloudVideoPlayer] No license key provided - ads will not work"),this.adPlayer=Su(this.video,{licenseKey:this.config.licenseKey||"",debug:null!==(t=this.config.debugAdTiming)&&void 0!==t&&t})}return e.prototype.load=function(){return x(this,void 0,void 0,function(){var e,t,r=this;return D(this,function(i){switch(i.label){case 0:return this.attached||this.attach(),this.shouldUseNativeHls()?(this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(e=this.config.lowLatencyMode)&&void 0!==e&&e,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using native HLS playback:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls}),this.adPlayer.initialize(),this.config.autoplay?[4,null===(t=this.video.play())||void 0===t?void 0:t.catch(function(){})]:[3,2]):[3,3];case 1:i.sent(),i.label=2;case 2:return[2];case 3:return this.hls=new mu(w(w({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:this.config.lowLatencyMode?1.5:1},this.config.lowLatencyMode?{liveSyncDuration:2}:{}),{maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:.5,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,startPosition:-1})),this.hls.on(mu.Events.MEDIA_ATTACHED,function(){var e;null===(e=r.hls)||void 0===e||e.loadSource(r.config.src)}),this.hls.on(mu.Events.MANIFEST_PARSED,function(){return x(r,void 0,void 0,function(){var e,t,r,i,n,a;return D(this,function(s){switch(s.label){case 0:return this.isLiveStream=null!==(i=null===(r=null===(t=this.hls)||void 0===t?void 0:t.levels)||void 0===r?void 0:r.some(function(e){var t,r;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(r=null==e?void 0:e.details)||void 0===r?void 0:r.type)}))&&void 0!==i&&i,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream}),this.adPlayer.initialize(),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,e=null!==(n=this.config.minSegmentsBeforePlay)&&void 0!==n?n:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",e,"segments to buffer before playback"),0!==e&&this.config.autoplay?[3,2]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(a=this.video.play())||void 0===a?void 0:a.catch(function(){})]:[3,2]);case 1:s.sent(),s.label=2;case 2:return[2]}})})}),this.hls.on(mu.Events.FRAG_BUFFERED,function(){return x(r,void 0,void 0,function(){var e,t,r,i=this;return D(this,function(n){switch(n.label){case 0:return this.hasInitialBufferCompleted?[2]:(this.bufferedSegmentsCount++,e=null!==(t=this.config.minSegmentsBeforePlay)&&void 0!==t?t:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Buffered segment ".concat(this.bufferedSegmentsCount,"/").concat(e)),this.bufferedSegmentsCount>=e?(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete. Starting playback."),[4,null===(r=this.video.play())||void 0===r?void 0:r.catch(function(e){i.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})]):[3,2]):[3,2]);case 1:n.sent(),n.label=2;case 2:return[2]}})})}),this.hls.on(mu.Events.FRAG_PARSING_METADATA,function(e,t){((null==t?void 0:t.samples)||[]).map(function(e){return{key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts}}).forEach(function(e){return r.onId3Tag(e)})}),this.hls.on(mu.Events.FRAG_CHANGED,function(e,t){var i,n,a,s,o,l,u=null==t?void 0:t.frag,c=null==u?void 0:u.tagList;if(Array.isArray(c))try{for(var d=C(c),h=d.next();!h.done;h=d.next()){var f=h.value,v="",g="";if(Array.isArray(f))v=String(null!==(a=f[0])&&void 0!==a?a:""),g=String(null!==(s=f[1])&&void 0!==s?s:"");else if("string"==typeof f){var p=f.indexOf(":");p>=0?(v=f.substring(0,p),g=f.substring(p+1)):(v=f,g="")}if(v)if(v.includes("EXT-X-CUE-OUT")){var m=r.parseCueOutDuration(g);r.onScte35Marker(w(w({type:"start"},void 0!==m?{durationSeconds:m}:{}),{raw:{tag:v,value:g}}))}else if(v.includes("EXT-X-CUE-OUT-CONT")){var y=r.parseCueOutCont(g);r.onScte35Marker(w(w(w({type:"progress"},void 0!==(null==y?void 0:y.duration)?{durationSeconds:y.duration}:{}),void 0!==(null==y?void 0:y.elapsed)?{ptsSeconds:y.elapsed}:{}),{raw:{tag:v,value:g}}))}else if(v.includes("EXT-X-CUE-IN"))r.onScte35Marker({type:"end",raw:{tag:v,value:g}});else if(v.includes("EXT-X-DATERANGE")){var E=r.parseAttributeList(g),k="SCTE35-OUT"in E,T="SCTE35-IN"in E,S=String(null!==(o=E.CLASS)&&void 0!==o?o:""),b=null!==(l=r.toNumber(E.DURATION))&&void 0!==l?l:r.toNumber(E["PLANNED-DURATION"]);(k||/com\.apple\.hls\.cue/i.test(S))&&r.onScte35Marker(w(w({type:"start"},void 0!==b?{durationSeconds:b}:{}),{raw:{tag:v,value:g,attrs:E}})),T&&r.onScte35Marker({type:"end",raw:{tag:v,value:g,attrs:E}})}}}catch(e){i={error:e}}finally{try{h&&!h.done&&(n=d.return)&&n.call(d)}finally{if(i)throw i.error}}}),this.hls.on(mu.Events.ERROR,function(e,t){var i,n;if(null==t?void 0:t.fatal)switch(t.type){case mu.ErrorTypes.NETWORK_ERROR:null===(i=r.hls)||void 0===i||i.startLoad();break;case mu.ErrorTypes.MEDIA_ERROR:null===(n=r.hls)||void 0===n||n.recoverMediaError();break;default:r.destroy()}}),this.hls.attachMedia(this.video),[2]}})})},e.prototype.attach=function(){var e=this;this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.adPlayer.initialize(),this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.adPlayer.on("all_ads_completed",function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad completed - ending ad break"),e.inAdBreak&&e.handleAdPodComplete()}),this.adPlayer.on("ad_error",function(){console.error("[StormcloudVideoPlayer] Ad error occurred"),e.inAdBreak&&e.handleAdPodComplete()}),this.adPlayer.on("content_pause",function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Content paused for ad")}),this.adPlayer.on("content_resume",function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Content resuming after ad")}),this.timeUpdateHandler=function(){},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.nativeHlsMode&&e.videoSrcProtection&&!e.adPlayer.isAdPlaying()){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring");var t=e.video.currentTime,r=e.video.paused;e.video.src=e.videoSrcProtection,e.video.currentTime=t,r||e.video.play().catch(function(){})}},this.video.addEventListener("emptied",this.emptiedHandler))},e.prototype.shouldUseNativeHls=function(){if("other"===this.getStreamType())return!0;var e=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!e)},e.prototype.onId3Tag=function(e){"number"==typeof e.ptsSeconds&&this.updatePtsDrift(e.ptsSeconds);var t=this.parseScte35FromId3(e);t&&this.onScte35Marker(t)},e.prototype.parseScte35FromId3=function(e){var t,r,i=this.decodeId3ValueToText(e.value);if(i){var n=i.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||i.match(/CUE-OUT(?::([^\r\n]*))?/i);if(n){var a=(null!==(t=n[1])&&void 0!==t?t:"").trim(),s=this.parseCueOutDuration(a);return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==s?{durationSeconds:s}:{}),{raw:{id3:i}})}var o=i.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(o){a=(null!==(r=o[1])&&void 0!==r?r:"").trim();var l=this.parseCueOutCont(a);return w(w(w({type:"progress"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==(null==l?void 0:l.duration)?{durationSeconds:l.duration}:{}),{raw:{id3:i}})}return i.match(/EXT-X-CUE-IN\b/i)||i.match(/CUE-IN\b/i)?w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:i}}):void 0}},e.prototype.decodeId3ValueToText=function(e){try{if("string"==typeof e)return e;var t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;for(var r="",i=0;i<e.length;i++)r+=String.fromCharCode(e[i]);return r}catch(e){return}},e.prototype.onScte35Marker=function(e){return x(this,void 0,void 0,function(){var t;return D(this,function(r){switch(r.label){case 0:return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime}),"start"!==e.type?[3,2]:this.inAdBreak?[2]:(this.inAdBreak=!0,t=null!=e.durationSeconds?1e3*e.durationSeconds:3e4,this.expectedAdBreakDurationMs=t,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad break:",{durationMs:t,durationSeconds:e.durationSeconds}),this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),[4,this.handleAdStart(e)]);case 1:return r.sent(),null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs),[2];case 2:return"progress"===e.type&&this.inAdBreak?(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),[2]):"end"!==e.type?[3,5]:this.inAdBreak?(this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.clearAdStopTimer(),this.adPlayer.isAdPlaying()?[4,this.adPlayer.stop()]:[3,4]):[2];case 3:r.sent(),r.label=4;case 4:return this.handleAdPodComplete(),[2];case 5:return[2]}})})},e.prototype.handleAdStart=function(e){return x(this,void 0,void 0,function(){var t,r,i;return D(this,function(n){switch(n.label){case 0:t=null!==(i=e.durationSeconds)&&void 0!==i?i:30,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Requesting ads for duration:",t),n.label=1;case 1:return n.trys.push([1,4,,5]),[4,this.adPlayer.requestAds(String(t))];case 2:return n.sent(),[4,this.adPlayer.play()];case 3:return n.sent(),[3,5];case 4:return r=n.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Ad request/play failed:",r),this.handleAdPodComplete(),[3,5];case 5:return[2]}})})},e.prototype.parseCueOutDuration=function(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var r=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(r&&null!=r[1]){var i=parseFloat(r[1]);return Number.isNaN(i)?void 0:i}},e.prototype.parseCueOutCont=function(e){var t=e.match(/Elapsed\s*=\s*([0-9.]+)/i),r=e.match(/Duration\s*=\s*([0-9.]+)/i),i={};if(t&&null!=t[1]){var n=parseFloat(t[1]);Number.isNaN(n)||(i.elapsed=n)}if(r&&null!=r[1]){var a=parseFloat(r[1]);Number.isNaN(a)||(i.duration=a)}if("elapsed"in i||"duration"in i)return i},e.prototype.parseAttributeList=function(e){for(var t,r,i,n,a={},s=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(n=s.exec(e));){var o=null!==(t=n[1])&&void 0!==t?t:"",l=null!==(i=null!==(r=n[3])&&void 0!==r?r:n[4])&&void 0!==i?i:"";l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),o&&(a[o]=l)}return a},e.prototype.toNumber=function(e){if(null!=e){var t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}},e.prototype.scheduleAdStopCountdown=function(e){var t=this;this.clearAdStopTimer();var r=Math.max(0,Math.floor(e));0!==r?this.adStopTimerId=window.setTimeout(function(){t.handleAdPodComplete()},r):this.handleAdPodComplete()},e.prototype.clearAdStopTimer=function(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)},e.prototype.updatePtsDrift=function(e){var t=1e3*(this.video.currentTime-e);if(Number.isFinite(t)&&!(Math.abs(t)>6e4)){this.ptsDriftEmaMs=.9*this.ptsDriftEmaMs+.1*t}},e.prototype.handleAdPodComplete=function(){var e;this.clearAdStopTimer(),this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.adPlayer.stop().catch(function(){});var t=this.adPlayer.getOriginalMutedState(),r=this.adPlayer.getOriginalVolume();this.video.muted!==t&&(this.video.muted=t),Math.abs(this.video.volume-r)>.01&&(this.video.volume=r),this.video.paused&&(null===(e=this.video.play())||void 0===e||e.catch(function(){})),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad break complete")},e.prototype.isAdPlaying=function(){return this.inAdBreak&&this.adPlayer.isAdPlaying()},e.prototype.isShowingAds=function(){return this.adPlayer.isAdPlaying()},e.prototype.getStreamType=function(){var e=this.config.src.toLowerCase();return e.includes(".m3u8")||e.includes("/hls/")||e.includes("application/vnd.apple.mpegurl")?"hls":"other"},e.prototype.shouldShowNativeControls=function(){var e,t;return"other"===this.getStreamType()?!(null!==(e=this.config.showCustomControls)&&void 0!==e&&e):!(!this.config.allowNativeHls||null!==(t=this.config.showCustomControls)&&void 0!==t&&t)},e.prototype.toggleMute=function(){if(this.adPlayer.isAdPlaying()){var e=!this.video.muted;this.adPlayer.updateOriginalMutedState(e,this.video.volume),this.adPlayer.setAdVolume(e?0:1)}else this.video.muted=!this.video.muted,this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume)},e.prototype.toggleFullscreen=function(){var e=this;return new Promise(function(t,r){if(document.fullscreenElement)document.exitFullscreen().then(function(){return t()}).catch(r);else{var i=e.video.parentElement;if(!i)return void r(new Error("No parent container found for fullscreen"));i.requestFullscreen().then(function(){return t()}).catch(r)}})},e.prototype.isMuted=function(){return this.video.muted},e.prototype.setMuted=function(e){this.video.muted=e,this.adPlayer.updateOriginalMutedState(e,this.video.volume),this.adPlayer.isAdPlaying()&&this.adPlayer.setAdVolume(e?0:1)},e.prototype.setVolume=function(e){var t=Math.max(0,Math.min(1,e));this.adPlayer.isAdPlaying()?(this.adPlayer.setAdVolume(t),this.adPlayer.updateOriginalMutedState(0===t,t)):(this.video.volume=t,this.video.muted=0===t,this.adPlayer.updateOriginalMutedState(0===t,t))},e.prototype.isFullscreen=function(){return!!document.fullscreenElement},e.prototype.isLive=function(){return this.isLiveStream},Object.defineProperty(e.prototype,"videoElement",{get:function(){return this.video},enumerable:!1,configurable:!0}),e.prototype.resize=function(){if(this.adPlayer&&this.adPlayer.isAdPlaying()){var e=this.video.clientWidth||640,t=this.video.clientHeight||360;this.adPlayer.resize(e,t)}},e.prototype.destroy=function(){var e,t;this.clearAdStopTimer(),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.adPlayer)||void 0===t||t.destroy()},e.prototype.getCurrentAdIndex=function(){return 0},e.prototype.getTotalAdsInBreak=function(){return 1},e}(),wu={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Pu=z.createContext&&z.createContext(wu),xu=["attr","size","title"];function Du(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){if(t.indexOf(i)>=0)continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Cu(){return Cu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Cu.apply(this,arguments)}function _u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Mu(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?_u(Object(r),!0).forEach(function(t){Ou(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_u(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Ou(e,t,r){var i;return i=function(e,t){if("object"!=S(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=S(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==S(i)?i:i+"")in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Fu(e){return e&&e.map(function(e,t){return z.createElement(e.tag,Mu({key:t},e.attr),Fu(e.child))})}function Nu(e){return function(t){return z.createElement(Uu,Cu({attr:Mu({},e.attr)},t),Fu(e.child))}}function Uu(e){var t=function(t){var r,i=e.attr,n=e.size,a=e.title,s=Du(e,xu),o=n||t.size||"1em";return t.className&&(r=t.className),e.className&&(r=(r?r+" ":"")+e.className),z.createElement("svg",Cu({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,i,s,{className:r,style:Mu(Mu({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),a&&z.createElement("title",null,a),e.children)};return void 0!==Pu?z.createElement(Pu.Consumer,null,function(e){return t(e)}):t(wu)}function Bu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function Gu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M0 180V56c0-13.3 10.7-24 24-24h124c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H64v84c0 6.6-5.4 12-12 12H12c-6.6 0-12-5.4-12-12zM288 44v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12V56c0-13.3-10.7-24-24-24H300c-6.6 0-12 5.4-12 12zm148 276h-40c-6.6 0-12 5.4-12 12v84h-84c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24V332c0-6.6-5.4-12-12-12zM160 468v-40c0-6.6-5.4-12-12-12H64v-84c0-6.6-5.4-12-12-12H12c-6.6 0-12 5.4-12 12v124c0 13.3 10.7 24 24 24h124c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function Hu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z"},child:[]}]})(e)}function Vu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z"},child:[]}]})(e)}function Ku(e){return Nu({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"},child:[]}]})(e)}function ju(e){return Nu({tag:"svg",attr:{viewBox:"0 0 384 512"},child:[{tag:"path",attr:{d:"M215.03 72.04L126.06 161H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V89.02c0-21.47-25.96-31.98-40.97-16.98zm123.2 108.08c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 229.28 336 242.62 336 257c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.87z"},child:[]}]})(e)}function Yu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zM461.64 256l45.64-45.64c6.3-6.3 6.3-16.52 0-22.82l-22.82-22.82c-6.3-6.3-16.52-6.3-22.82 0L416 210.36l-45.64-45.64c-6.3-6.3-16.52-6.3-22.82 0l-22.82 22.82c-6.3 6.3-6.3 16.52 0 22.82L370.36 256l-45.63 45.63c-6.3 6.3-6.3 16.52 0 22.82l22.82 22.82c6.3 6.3 16.52 6.3 22.82 0L416 301.64l45.64 45.64c6.3 6.3 16.52 6.3 22.82 0l22.82-22.82c6.3-6.3 6.3-16.52 0-22.82L461.64 256z"},child:[]}]})(e)}function Wu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zm233.32-51.08c-11.17-7.33-26.18-4.24-33.51 6.95-7.34 11.17-4.22 26.18 6.95 33.51 66.27 43.49 105.82 116.6 105.82 195.58 0 78.98-39.55 152.09-105.82 195.58-11.17 7.32-14.29 22.34-6.95 33.5 7.04 10.71 21.93 14.56 33.51 6.95C528.27 439.58 576 351.33 576 256S528.27 72.43 448.35 19.97zM480 256c0-63.53-32.06-121.94-85.77-156.24-11.19-7.14-26.03-3.82-33.12 7.46s-3.78 26.21 7.41 33.36C408.27 165.97 432 209.11 432 256s-23.73 90.03-63.48 115.42c-11.19 7.14-14.5 22.07-7.41 33.36 6.51 10.36 21.12 15.14 33.12 7.46C447.94 377.94 480 319.54 480 256zm-141.77-76.87c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 228.28 336 241.63 336 256c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.86z"},child:[]}]})(e)}var qu=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs"],zu=z.memo(function(e){var t=e.src,r=e.autoplay,i=e.muted,n=e.lowLatencyMode,a=e.allowNativeHls,s=e.driftToleranceMs,o=e.immediateManifestAds,l=e.debugAdTiming,u=e.showCustomControls,c=e.hideLoadingIndicator,d=e.onVolumeToggle,h=e.onFullscreenToggle,f=e.onControlClick,v=e.onReady,g=e.wrapperClassName,p=e.wrapperStyle,m=e.className,y=e.style,E=e.controls,k=e.playsInline,T=e.preload,S=e.poster,b=e.children,A=e.licenseKey,L=e.minSegmentsBeforePlay,I=P(e,["src","autoplay","muted","lowLatencyMode","allowNativeHls","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","hideLoadingIndicator","onVolumeToggle","onFullscreenToggle","onControlClick","onReady","wrapperClassName","wrapperStyle","className","style","controls","playsInline","preload","poster","children","licenseKey","minSegmentsBeforePlay"]),R=q.useRef(null),x=q.useRef(null),D=q.useRef(null),C=_(z.useState({showAds:!1,currentIndex:0,totalAds:0}),2),M=C[0],O=C[1],F=_(z.useState(!0),2),N=F[0],U=F[1],B=_(z.useState(!1),2),G=B[0],H=B[1],V=_(z.useState(!1),2),K=V[0],j=V[1],Y=_(z.useState(!1),2),X=Y[0],Q=Y[1],$=_(z.useState(0),2),J=$[0],Z=$[1],ee=_(z.useState(0),2),te=ee[0],re=ee[1],ie=_(z.useState(1),2),ne=ie[0],ae=ie[1],se=_(z.useState(1),2),oe=se[0],le=se[1],ue=_(z.useState(!1),2),ce=ue[0],de=ue[1],he=_(z.useState(!1),2),fe=he[0],ve=he[1],ge=_(z.useState(!0),2),pe=ge[0],me=ge[1],ye=_(z.useState(!1),2),Ee=ye[0],ke=ye[1],Te=_(z.useState(!1),2),Se=Te[0],be=Te[1],Ae=_(z.useState(!1),2),Le=Ae[0],Ie=Ae[1],Re=_(z.useState("undefined"!=typeof window?window.innerWidth:1920),2),we=Re[0],Pe=Re[1],xe=_(z.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),De=xe[0],Ce=xe[1],_e=we<480?.7:we<768?.8:we<1024?.9:1,Me=function(e){if(!isFinite(e))return"0:00:00";var t=Math.floor(e/3600),r=Math.floor(e%3600/60),i=Math.floor(e%60);return"".concat(t,":").concat(r.toString().padStart(2,"0"),":").concat(i.toString().padStart(2,"0"))},Oe=function(e){if(x.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));x.current.setVolume(t)}},Fe=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),Ne=u&&(!Fe||a),Ue=q.useMemo(function(){return qu.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,a,A,n,s]);return q.useEffect(function(){if("undefined"!=typeof window){var e=R.current;if(e&&t){if(!A)return Ie(!0),me(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(Ie(!1),l&&console.log("[StormcloudUI] Initializing player, isLoading=true"),x.current){try{x.current.destroy()}catch(e){}x.current=null}var c={src:t,videoElement:e};void 0!==r&&(c.autoplay=r),void 0!==i&&(c.muted=i),void 0!==n&&(c.lowLatencyMode=n),void 0!==a&&(c.allowNativeHls=a),void 0!==s&&(c.driftToleranceMs=s),void 0!==o&&(c.immediateManifestAds=o),void 0!==l&&(c.debugAdTiming=l),void 0!==u&&(c.showCustomControls=u),void 0!==d&&(c.onVolumeToggle=d),void 0!==h&&(c.onFullscreenToggle=h),void 0!==f&&(c.onControlClick=f),void 0!==A&&(c.licenseKey=A),void 0!==L&&(c.minSegmentsBeforePlay=L);var g=new Ru(c);return x.current=g,g.load().then(function(){var e=g.shouldShowNativeControls();U(e),l&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==v||v(g)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),me(!1),null==v||v(g)}),function(){try{g.destroy()}catch(e){}x.current=null}}}},[Ue]),q.useEffect(function(){if(x.current)try{void 0!==r&&x.current.videoElement&&(x.current.videoElement.autoplay=r),void 0===i||x.current.isShowingAds()||x.current.setMuted(i)}catch(e){console.warn("Failed to update player properties:",e)}},[r,i]),q.useEffect(function(){if(x.current){var e=setInterval(function(){if(x.current){var e=x.current.isShowingAds(),t=x.current.getCurrentAdIndex(),r=x.current.getTotalAdsInBreak();O(function(i){return i.showAds!==e||i.currentIndex!==t||i.totalAds!==r?{showAds:e,currentIndex:t,totalAds:r}:i})}},100);return function(){return clearInterval(e)}}},[]),q.useEffect(function(){if("undefined"!=typeof window&&x.current){var e=function(){x.current&&R.current&&"function"==typeof x.current.resize&&x.current.resize(),Pe(window.innerWidth),Ce(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),q.useEffect(function(){if(x.current&&R.current){var e=setInterval(function(){var e;if(x.current&&R.current){H(x.current.isMuted()),Q(!R.current.paused);var t=R.current.currentTime;Z(isFinite(t)?t:0);var r=R.current.duration;re(isFinite(r)?r:0);var i=R.current.volume;ae(isFinite(i)?Math.max(0,Math.min(1,i)):1);var n=R.current.playbackRate;le(isFinite(n)&&n>0?n:1)}j(document.fullscreenElement===(null===(e=R.current)||void 0===e?void 0:e.parentElement))},200),t=function(){var e;j(document.fullscreenElement===(null===(e=R.current)||void 0===e?void 0:e.parentElement))};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),q.useEffect(function(){if(R.current){var e=function(){var e;R.current&&R.current.offsetHeight;l&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState)},t=function(){var e;l&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState)},r=function(){var e;l&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState)},i=function(){var e;me(!1),D.current&&(clearTimeout(D.current),D.current=null),ke(!1),l&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=function(){var e;me(!1),D.current&&(clearTimeout(D.current),D.current=null),ke(!1),l&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},a=function(){var e;D.current&&clearTimeout(D.current),D.current=window.setTimeout(function(){var e;ke(!0),l&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),l&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},s=function(){var e;me(!1),D.current&&(clearTimeout(D.current),D.current=null),ke(!1),be(!1),l&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=function(){x.current&&!x.current.isShowingAds()?be(!0):be(!1)},u=function(){be(!0)},c=R.current;return c.addEventListener("loadstart",r),c.addEventListener("loadedmetadata",e),c.addEventListener("loadeddata",t),c.addEventListener("canplay",i),c.addEventListener("canplaythrough",n),c.addEventListener("waiting",a),c.addEventListener("playing",s),c.addEventListener("pause",o),c.addEventListener("ended",u),c.paused&&be(!0),function(){D.current&&(clearTimeout(D.current),D.current=null),c.removeEventListener("loadstart",r),c.removeEventListener("loadedmetadata",e),c.removeEventListener("loadeddata",t),c.removeEventListener("canplay",i),c.removeEventListener("canplaythrough",n),c.removeEventListener("waiting",a),c.removeEventListener("playing",s),c.removeEventListener("pause",o),c.removeEventListener("ended",u)}}},[l]),W.jsxs(W.Fragment,{children:[W.jsx("style",{children:"\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n \n .stormcloud-loading-hidden .stormcloud-loading-indicator {\n display: none !important;\n }\n \n .stormcloud-video-wrapper:fullscreen {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n .stormcloud-video-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n *:fullscreen {\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n }\n "}),W.jsxs("div",{className:"stormcloud-video-wrapper ".concat(g||""),style:w({display:"flex",alignItems:"center",justifyContent:"center",position:K?"fixed":"relative",top:K?0:void 0,left:K?0:void 0,overflow:"hidden",width:K?"100vw":"100%",height:K?"100vh":"auto",minHeight:K?"100vh":"auto",maxWidth:K?"100vw":"100%",maxHeight:K?"100vh":"none",zIndex:K?999999:void 0,backgroundColor:K?"#000":void 0,borderRadius:K?0:void 0,boxShadow:K?"none":void 0},p),children:[W.jsx("video",w({ref:R,className:m,style:w({display:"block",width:"100%",height:K?"100%":"auto",maxWidth:"100%",maxHeight:K?"100%":"none",objectFit:K?"cover":"contain",backgroundColor:"#000",aspectRatio:K?"unset":void 0},y),controls:N&&E&&!u,playsInline:k,preload:T,poster:S},I,{children:b})),(pe||Ee)&&!c&&W.jsx(Ku,{className:"stormcloud-loading-indicator",size:42,color:"white",style:{position:"absolute",top:"calc(50% - 21px)",left:"calc(50% - 21px)",zIndex:20,animation:"spin 1s linear infinite",filter:"drop-shadow(0 3px 6px rgba(0, 0, 0, 0.8))"}}),Le&&W.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.9) 100%)",color:"white",padding:"24px 32px",borderRadius:"16px",backdropFilter:"blur(20px)",border:"2px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.6), inset 0 2px 0 rgba(255, 255, 255, 0.2)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[W.jsx("div",{style:{fontSize:"20px",fontWeight:"bold",marginBottom:"12px",color:"#ffffff",textShadow:"0 2px 4px rgba(0, 0, 0, 0.5)"},children:"License Key Required"}),W.jsxs("div",{style:{fontSize:"14px",lineHeight:"1.5",color:"rgba(255, 255, 255, 0.9)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.3)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",W.jsx("br",{}),"Contact your administrator for licensing information."]})]}),Se&&!pe&&!Ee&&!Le&&!M.showAds&&W.jsx("div",{onClick:function(){var e;R.current&&R.current.paused&&(R.current.src||R.current.currentSrc&&""!==R.current.currentSrc||R.current.readyState>=1?(null===(e=R.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),be(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",borderRadius:"50%",width:"100px",height:"100px",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",border:"3px solid rgba(255, 255, 255, 0.8)",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},onMouseEnter:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(40, 40, 40, 0.9) 100%)",t.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.borderColor="rgba(255, 255, 255, 0.9)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",t.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",t.style.borderColor="rgba(255, 255, 255, 0.8)"},title:"Play",children:W.jsx(Vu,{size:36,color:"white",style:{marginLeft:"6px",filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))"}})}),Ne&&!Le?W.jsx(W.Fragment,{children:W.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.8) 100%)",padding:"20px 16px 16px",zIndex:10},children:[W.jsxs("div",{style:{width:"100%",height:"8px",background:"linear-gradient(90deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%)",borderRadius:"8px",marginBottom:"16px",cursor:"pointer",position:"relative",backdropFilter:"blur(5px)",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"inset 0 2px 4px rgba(0, 0, 0, 0.2)"},onClick:function(e){if(R.current&&te>0&&isFinite(te)){var t=e.currentTarget.getBoundingClientRect(),r=e.clientX-t.left,i=Math.max(0,Math.min(1,r/t.width))*te;isFinite(i)&&i>=0&&i<=te&&(R.current.currentTime=i)}},children:[W.jsx("div",{style:{height:"100%",background:"linear-gradient(90deg, rgba(139, 92, 246, 0.9) 0%, rgba(59, 130, 246, 0.8) 50%, rgba(34, 197, 94, 0.9) 100%)",borderRadius:"8px",width:"".concat(te>0?J/te*100:0,"%"),transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 2px 8px rgba(139, 92, 246, 0.4)"}}),W.jsx("div",{style:{position:"absolute",top:"-6px",right:"".concat(te>0?100-J/te*100:100,"%"),width:"20px",height:"20px",background:"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(240, 240, 240, 0.9) 100%)",borderRadius:"50%",border:"3px solid rgba(139, 92, 246, 0.8)",boxShadow:"0 4px 16px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.8)",transform:"translateX(50%)",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"}})]}),W.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",flexWrap:we<768?"wrap":"nowrap",gap:"".concat(8*_e,"px")},children:[W.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*_e,"px"),flexWrap:we<480?"wrap":"nowrap"},children:[W.jsx("button",{onClick:function(){var e;R.current&&(R.current.paused?R.current.src||R.current.currentSrc&&""!==R.current.currentSrc||R.current.readyState>=1?(null===(e=R.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),be(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"):(R.current.pause(),be(!0)))},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",backdropFilter:"blur(12px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(10*_e,"px"),borderRadius:"".concat(16*_e,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)",minWidth:"".concat(48*_e,"px"),minHeight:"".concat(48*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)",t.style.boxShadow="0 12px 48px rgba(0, 0, 0, 0.6), 0 6px 24px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.4)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",t.style.boxShadow="0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)"},title:X?"Pause":"Play",children:X?W.jsx(Hu,{size:Math.max(16,20*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Vu,{size:Math.max(16,20*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),W.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)},children:[W.jsx("button",{onClick:function(){x.current&&x.current.toggleMute(),d&&d()},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*_e,"px"),borderRadius:"".concat(16*_e,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*_e,"px"),minHeight:"".concat(44*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:G?"Unmute":"Mute",children:G||0===ne?W.jsx(Yu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):ne<.5?W.jsx(ju,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Wu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),ce&&W.jsxs(W.Fragment,{children:[W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)}}),W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.88) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(15px)",padding:"10px 14px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){de(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.6), 0 6px 16px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 0 24px rgba(59, 130, 246, 0.3)",e.currentTarget.style.borderColor="rgba(59, 130, 246, 0.4)"},onMouseLeave:function(e){de(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.15)"},children:W.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseEnter:function(e){},onMouseLeave:function(e){},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){if(t){var r=t.getBoundingClientRect(),i=e.clientY-r.top,n=1-Math.max(0,Math.min(1,i/r.height));Oe(n)}},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect(),a=e.clientY-n.top,s=1-Math.max(0,Math.min(1,a/n.height));Oe(s)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),r=e.clientY-t.top,i=1-Math.max(0,Math.min(1,r/t.height));Oe(i)},children:[W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.15) 100%)",borderRadius:"4px",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.2)"}}),W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(G?0:ne),"%"),background:"linear-gradient(180deg, rgba(96, 165, 250, 1) 0%, rgba(59, 130, 246, 0.95) 50%, rgba(37, 99, 235, 0.9) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 8px rgba(59, 130, 246, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.3)"}}),W.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(G?0:ne),"% - 7px)"),left:"50%",transform:"translateX(-50%)",width:"14px",height:"14px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 3px 10px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(59, 130, 246, 0.5), 0 0 20px rgba(59, 130, 246, 0.6)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),W.jsxs("div",{style:{fontSize:"".concat(14*_e,"px"),fontFamily:"monospace",color:"rgba(255, 255, 255, 0.9)",display:we<480?"none":"block"},children:[Me(J)," / ",Me(te)]})]}),W.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*_e,"px")},children:[W.jsxs("div",{style:{position:"relative",display:we<600?"none":"block"},children:[W.jsxs("button",{onClick:function(){return ve(!fe)},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*_e,"px ").concat(14*_e,"px"),borderRadius:"".concat(14*_e,"px"),fontSize:"".concat(14*_e,"px"),fontFamily:"monospace",fontWeight:"700",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(56*_e,"px"),minHeight:"".concat(40*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 32px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:"Playback Speed",children:[oe,"x"]}),fe&&W.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"12px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.95) 100%)",backdropFilter:"blur(20px)",borderRadius:"12px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"90px",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1)"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(function(e){return W.jsxs("button",{onClick:function(){return t=e,R.current&&isFinite(t)&&t>0&&(R.current.playbackRate=t),void ve(!1);var t},style:{display:"block",width:"100%",padding:"10px 16px",background:oe===e?"linear-gradient(135deg, rgba(99, 102, 241, 0.8) 0%, rgba(139, 92, 246, 0.6) 100%)":"transparent",border:"none",color:"white",cursor:"pointer",fontSize:"13px",fontFamily:"monospace",fontWeight:"600",textAlign:"center",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",borderBottom:2!==e?"1px solid rgba(255, 255, 255, 0.05)":"none"},onMouseEnter:function(t){oe!==e&&(t.target.style.background="linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%)")},onMouseLeave:function(t){oe!==e&&(t.target.style.background="transparent")},children:[e,"x"]},e)})})]}),W.jsx("button",{onClick:function(){h?h():x.current&&x.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*_e,"px"),borderRadius:"".concat(16*_e,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*_e,"px"),minHeight:"".concat(44*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:K?"Exit Fullscreen":"Enter Fullscreen",children:K?W.jsx(Bu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Gu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}})})]})]})]})}):u&&!Le&&W.jsxs("div",{style:{position:"absolute",bottom:"".concat(10*_e,"px"),right:"".concat(10*_e,"px"),transform:"none",display:"flex",flexDirection:De?"column":"row",gap:"".concat(10*_e,"px"),zIndex:10},children:[W.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)},children:[W.jsx("button",{onClick:function(){x.current&&x.current.toggleMute(),d&&d()},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*_e,"px"),padding:"".concat(8*_e,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*_e,"px"),minHeight:"".concat(46*_e,"px")},title:G?"Unmute":"Mute",children:G||0===ne?W.jsx(Yu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):ne<.5?W.jsx(ju,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):W.jsx(Wu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})}),ce&&W.jsxs(W.Fragment,{children:[W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)}}),W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.96) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(20px)",padding:"10px 14px",borderRadius:"14px",border:"2px solid rgba(255, 255, 255, 0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){de(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), 0 6px 16px rgba(0, 0, 0, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 24px rgba(96, 165, 250, 0.4)",e.currentTarget.style.borderColor="rgba(96, 165, 250, 0.8)"},onMouseLeave:function(e){de(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.7)"},children:W.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){if(t){var r=t.getBoundingClientRect(),i=e.clientY-r.top,n=1-Math.max(0,Math.min(1,i/r.height));Oe(n)}},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect(),a=e.clientY-n.top,s=1-Math.max(0,Math.min(1,a/n.height));Oe(s)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),r=e.clientY-t.top,i=1-Math.max(0,Math.min(1,r/t.height));Oe(i)},children:[W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.85) 0%, rgba(255, 255, 255, 0.5) 100%)",borderRadius:"4px",border:"1px solid rgba(255, 255, 255, 0.4)",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.3)"}}),W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(G?0:ne),"%"),background:"linear-gradient(180deg, rgba(125, 211, 252, 1) 0%, rgba(96, 165, 250, 0.98) 50%, rgba(59, 130, 246, 0.95) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 12px rgba(96, 165, 250, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.4)"}}),W.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(G?0:ne),"% - 8px)"),left:"50%",transform:"translateX(-50%)",width:"16px",height:"16px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",border:"2px solid rgba(96, 165, 250, 0.9)",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.6), 0 0 0 3px rgba(96, 165, 250, 0.6), 0 0 24px rgba(96, 165, 250, 0.7)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),W.jsx("button",{onClick:function(){h?h():x.current&&x.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*_e,"px"),padding:"".concat(8*_e,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*_e,"px"),minHeight:"".concat(46*_e,"px")},title:K?"Exit Fullscreen":"Enter Fullscreen",children:K?W.jsx(Bu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):W.jsx(Gu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})})]}),f&&W.jsx("div",{onClick:f,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var r,i,n,a,s,o;try{for(var l=C(qu),u=l.next();!u.done;u=l.next()){if(e[v=u.value]!==t[v])return!1}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}try{for(var c=C(["autoplay","muted","controls","showCustomControls","className","style","wrapperClassName","wrapperStyle","playsInline","preload","poster","children"]),d=c.next();!d.done;d=c.next()){if(e[v=d.value]!==t[v])return!1}}catch(e){n={error:e}}finally{try{d&&!d.done&&(a=c.return)&&a.call(c)}finally{if(n)throw n.error}}try{for(var h=C(["onReady","onVolumeToggle","onFullscreenToggle","onControlClick"]),f=h.next();!f.done;f=h.next()){var v;if(e[v=f.value]!==t[v])return!1}}catch(e){s={error:e}}finally{try{f&&!f.done&&(o=h.return)&&o.call(h)}finally{if(s)throw s.error}}return!0}),Xu=function(){},Qu={playing:!1,loop:!1,controls:!0,volume:1,muted:!1,playbackRate:1,width:"100%",height:"auto",style:{},progressInterval:1e3,playsInline:!1,autoplay:!1,preload:"metadata",poster:"",className:"",wrapperClassName:"",wrapperStyle:{},allowNativeHls:!1,lowLatencyMode:!1,driftToleranceMs:1e3,immediateManifestAds:!0,debugAdTiming:!1,showCustomControls:!1,hideLoadingIndicator:!1,licenseKey:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:Xu,onPlay:Xu,onPause:Xu,onBuffer:Xu,onBufferEnd:Xu,onEnded:Xu,onError:Xu,onDuration:Xu,onSeek:Xu,onProgress:Xu,onVolumeToggle:Xu,onFullscreenToggle:Xu,onControlClick:Xu},$u=q.lazy,Ju=function(e,t){var r=w({},e);return t.forEach(function(e){delete r[e]}),r},Zu=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},ec=function(e){for(var t,r,i=[],n=1;n<arguments.length;n++)i[n-1]=arguments[n];if(!i.length)return e;var a=i.shift();if(tc(e)&&tc(a))for(var s in a)tc(a[s])?(e[s]||Object.assign(e,((t={})[s]={},t)),ec(e[s],a[s])):Object.assign(e,((r={})[s]=a[s],r));return ec.apply(void 0,M([e],_(i),!1))},tc=function(e){return e&&"object"===S(e)&&!Array.isArray(e)},rc="undefined"!=typeof window&&window.document,ic="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,nc=rc&&/iPad|iPhone|iPod/.test(navigator.userAgent),ac=rc&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),sc=/\.(m3u8)($|\?)/i,oc=/\/hls\//i,lc=/\.(mpd)($|\?)/i,uc=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,cc=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,dc={hls:function(e){return!(!e||"string"!=typeof e)&&(sc.test(e)||oc.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&lc.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&uc.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&cc.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(uc.test(e)||cc.test(e))}},hc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return x(t,void 0,void 0,function(){var e,t,r,i,n,a,s,o;return D(this,function(l){switch(l.label){case 0:if(!this.props.videoElement||!this.props.src)return[2];l.label=1;case 1:return l.trys.push([1,3,,4]),this.player&&(this.player.destroy(),this.player=null),e={src:this.props.src,videoElement:this.props.videoElement},void 0!==this.props.autoplay&&(e.autoplay=this.props.autoplay),void 0!==this.props.muted&&(e.muted=this.props.muted),void 0!==this.props.lowLatencyMode&&(e.lowLatencyMode=this.props.lowLatencyMode),void 0!==this.props.allowNativeHls&&(e.allowNativeHls=this.props.allowNativeHls),void 0!==this.props.driftToleranceMs&&(e.driftToleranceMs=this.props.driftToleranceMs),void 0!==this.props.immediateManifestAds&&(e.immediateManifestAds=this.props.immediateManifestAds),void 0!==this.props.debugAdTiming&&(e.debugAdTiming=this.props.debugAdTiming),void 0!==this.props.showCustomControls&&(e.showCustomControls=this.props.showCustomControls),void 0!==this.props.onVolumeToggle&&(e.onVolumeToggle=this.props.onVolumeToggle),void 0!==this.props.onFullscreenToggle&&(e.onFullscreenToggle=this.props.onFullscreenToggle),void 0!==this.props.onControlClick&&(e.onControlClick=this.props.onControlClick),void 0!==this.props.licenseKey&&(e.licenseKey=this.props.licenseKey),void 0!==this.props.adFailsafeTimeoutMs&&(e.adFailsafeTimeoutMs=this.props.adFailsafeTimeoutMs),void 0!==this.props.minSegmentsBeforePlay&&(e.minSegmentsBeforePlay=this.props.minSegmentsBeforePlay),this.player=new Ru(e),null===(i=(r=this.props).onMount)||void 0===i||i.call(r,this),[4,this.player.load()];case 2:return l.sent(),this.mounted&&(null===(a=(n=this.props).onReady)||void 0===a||a.call(n)),[3,4];case 3:return t=l.sent(),this.mounted&&(null===(o=(s=this.props).onError)||void 0===o||o.call(s,t)),[3,4];case 4:return[2]}})})},t.play=function(){var e,r,i;if(t.props.videoElement){var n=t.props.videoElement;n.src||n.currentSrc&&""!==n.currentSrc||n.readyState>=1?(null===(e=n.play())||void 0===e||e.catch(function(e){var r,i;console.error("[HlsPlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}),null===(i=(r=t.props).onPlay)||void 0===i||i.call(r)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},t.pause=function(){var e,r;t.props.videoElement&&(t.props.videoElement.pause(),null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"player"===e?t.player:"video"===e?t.props.videoElement:"hls"===e&&t.player?t.player.hls:null},t}return R(t,e),t.prototype.componentDidMount=function(){this.mounted=!0,this.load()},t.prototype.componentWillUnmount=function(){this.mounted=!1,this.player&&(this.player.destroy(),this.player=null)},t.prototype.componentDidUpdate=function(e){e.src!==this.props.src&&this.load()},t.prototype.render=function(){return null},t.displayName="HlsPlayer",t.canPlay=dc.hls,t}(q.Component),fc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,r;if(t.props.videoElement&&t.props.src){var i=t.props.videoElement,n=function(){var e,r;t.mounted&&!t.ready&&(t.ready=!0,null===(r=(e=t.props).onReady)||void 0===r||r.call(e))},a=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPlay)||void 0===r||r.call(e))},s=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},o=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onEnded)||void 0===r||r.call(e))},l=function(e){var r,i;t.mounted&&(null===(i=(r=t.props).onError)||void 0===i||i.call(r,e))},u=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onLoaded)||void 0===r||r.call(e))};return i.addEventListener("loadedmetadata",n),i.addEventListener("play",a),i.addEventListener("pause",s),i.addEventListener("ended",o),i.addEventListener("error",l),i.addEventListener("loadeddata",u),i.src=t.props.src,void 0!==t.props.autoplay&&(i.autoplay=t.props.autoplay),void 0!==t.props.muted&&(i.muted=t.props.muted),void 0!==t.props.loop&&(i.loop=t.props.loop),void 0!==t.props.controls&&(i.controls=t.props.controls),void 0!==t.props.playsInline&&(i.playsInline=t.props.playsInline),void 0!==t.props.preload&&(i.preload=t.props.preload),void 0!==t.props.poster&&(i.poster=t.props.poster),null===(r=(e=t.props).onMount)||void 0===r||r.call(e,t),function(){i.removeEventListener("loadedmetadata",n),i.removeEventListener("play",a),i.removeEventListener("pause",s),i.removeEventListener("ended",o),i.removeEventListener("error",l),i.removeEventListener("loadeddata",u)}}},t.play=function(){var e;if(t.props.videoElement){var r=t.props.videoElement;r.src||r.currentSrc&&""!==r.currentSrc||r.readyState>=1?null===(e=r.play())||void 0===e||e.catch(function(e){var r,i;console.error("[FilePlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},t.pause=function(){t.props.videoElement&&t.props.videoElement.pause()},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.setLoop=function(e){t.props.videoElement&&(t.props.videoElement.loop=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"video"===e?t.props.videoElement:null},t.enablePIP=function(){return x(t,void 0,void 0,function(){var e;return D(this,function(t){switch(t.label){case 0:if(!this.props.videoElement||!("requestPictureInPicture"in this.props.videoElement))return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.props.videoElement.requestPictureInPicture()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Picture-in-Picture failed:",e),[3,4];case 4:return[2]}})})},t.disablePIP=function(){return x(t,void 0,void 0,function(){var e;return D(this,function(t){switch(t.label){case 0:if(!document.pictureInPictureElement)return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,document.exitPictureInPicture()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Exit Picture-in-Picture failed:",e),[3,4];case 4:return[2]}})})},t}return R(t,e),t.prototype.componentDidMount=function(){this.mounted=!0,this.load()},t.prototype.componentWillUnmount=function(){this.mounted=!1},t.prototype.componentDidUpdate=function(e){e.src!==this.props.src&&this.load()},t.prototype.render=function(){return null},t.displayName="FilePlayer",t.canPlay=dc.file,t}(q.Component),vc=[{key:"hls",name:"HLS Player",canPlay:dc.hls,lazyPlayer:$u(function(){return Promise.resolve({default:hc})})},{key:"file",name:"File Player",canPlay:dc.file,canEnablePIP:function(e){return dc.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:$u(function(){return Promise.resolve({default:fc})})}],gc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.mounted=!1,t.isReady=!1,t.isPlaying=!1,t.isLoading=!0,t.loadOnReady=null,t.startOnPlay=!0,t.seekOnPlay=null,t.onDurationCalled=!1,t.handlePlayerMount=function(e){t.player||(t.player=e,t.player.load(t.props.src)),t.progress()},t.getInternalPlayer=function(e){return t.player?t.player.getInternalPlayer(e):null},t.progress=function(){var e,r;if(t.props.src&&t.player&&t.isReady){var i=t.getCurrentTime()||0,n=t.getSecondsLoaded(),a=t.getDuration();if(a){var s={playedSeconds:i,played:i/a,loaded:0,loadedSeconds:0};null!==n&&(s.loadedSeconds=n,s.loaded=n/a),s.playedSeconds===t.prevPlayed&&s.loadedSeconds===t.prevLoaded||null===(r=(e=t.props).onProgress)||void 0===r||r.call(e,s),t.prevPlayed=s.playedSeconds,t.prevLoaded=s.loadedSeconds}}t.progressTimeout=window.setTimeout(t.progress,t.props.progressInterval||1e3)},t.handleReady=function(){if(t.mounted){t.isReady=!0,t.isLoading=!1;var e=t.props,r=e.onReady,i=e.playing,n=e.volume,a=e.muted;r(),a||null===n||t.player.setVolume(n),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):i&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,r=e.onStart,i=e.onPlay,n=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==n&&t.player.setPlaybackRate(n),null==r||r(),t.startOnPlay=!1),null==i||i(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var r,i;t.isPlaying=!1,t.isLoading||null===(i=(r=t.props).onPause)||void 0===i||i.call(r,e)},t.handleEnded=function(){var e=t.props,r=e.activePlayer,i=e.loop,n=e.onEnded;r.loopOnEnded&&i&&t.seekTo(0),i||(t.isPlaying=!1,null==n||n())},t.handleError=function(){for(var e,r,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];t.isLoading=!1,null===(r=(e=t.props).onError)||void 0===r||r.call(e,i[0],i[1],i[2],i[3])},t.handleDurationCheck=function(){var e,r;clearTimeout(t.durationCheckTimeout);var i=t.getDuration();i?t.onDurationCalled||(null===(r=(e=t.props).onDuration)||void 0===r||r.call(e,i),t.onDurationCalled=!0):t.durationCheckTimeout=window.setTimeout(t.handleDurationCheck,100)},t.handleLoaded=function(){t.isLoading=!1},t}return R(t,e),t.prototype.componentDidMount=function(){this.mounted=!0},t.prototype.componentWillUnmount=function(){clearTimeout(this.progressTimeout),clearTimeout(this.durationCheckTimeout),this.mounted=!1},t.prototype.componentDidUpdate=function(e){var t=this;if(this.player){var r=this.props,i=r.src,n=r.playing,a=r.volume,s=r.muted,o=r.playbackRate,l=r.loop,u=r.activePlayer;if(e.src!==i){if(this.isLoading&&!u.forceLoad&&!Zu(i))return console.warn("StormcloudPlayer: the attempt to load ".concat(i," is being deferred until the player has loaded")),void(this.loadOnReady=i||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(i,this.isReady)}e.playing||!n||this.isPlaying||this.player.play(),e.playing&&!n&&this.isPlaying&&this.player.pause(),e.volume!==a&&null!==a&&this.player.setVolume(a),e.muted!==s&&(s?this.player.mute():(this.player.unmute(),null!==a&&setTimeout(function(){return t.player.setVolume(a)}))),e.playbackRate!==o&&this.player.setPlaybackRate&&this.player.setPlaybackRate(o),e.loop!==l&&this.player.setLoop&&this.player.setLoop(l)}},t.prototype.getDuration=function(){return this.isReady?this.player.getDuration():null},t.prototype.getCurrentTime=function(){return this.isReady?this.player.getCurrentTime():null},t.prototype.getSecondsLoaded=function(){return this.isReady?this.player.getSecondsLoaded():null},t.prototype.seekTo=function(e,t,r){var i=this;if(this.isReady){if(t?"fraction"===t:e>0&&e<1){var n=this.player.getDuration();return n?void this.player.seekTo(n*e,r):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,r)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){i.seekOnPlay=null},5e3))},t.prototype.render=function(){var e=this.props.activePlayer;return e?z.createElement(e,w(w({},this.props),{onMount:this.handlePlayerMount,onReady:this.handleReady,onPlay:this.handlePlay,onPause:this.handlePause,onEnded:this.handleEnded,onLoaded:this.handleLoaded,onError:this.handleError})):null},t.displayName="Player",t.defaultProps=Qu,t}(q.Component),pc="undefined"!=typeof window&&window.document,mc="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,yc=pc||mc?q.Suspense:function(){return null},Ec=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","adFailsafeTimeoutMs","minSegmentsBeforePlay","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],kc=[],Tc=function(e,t){var r;return r=function(r){function i(){var i=r.apply(this,M([],_(arguments),!1))||this;return i.state={showPreview:!1},i.references={wrapper:function(e){i.wrapper=e},player:function(e){i.player=e}},i.getActivePlayer=function(r){var i,n;if(!r)return null;try{for(var a=C(M(M([],_(kc),!1),_(e),!1)),s=a.next();!s.done;s=a.next()){var o=s.value;if(o.canPlay(r))return o}}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(i)throw i.error}}return t||null},i.getAttributes=function(e){return Ju(i.props,Ec)},i.handleReady=function(){var e,t;null===(t=(e=i.props).onReady)||void 0===t||t.call(e,i)},i.seekTo=function(e,t,r){if(!i.player)return null;i.player.seekTo(e,t,r)},i.getCurrentTime=function(){return i.player?i.player.getCurrentTime():null},i.getSecondsLoaded=function(){return i.player?i.player.getSecondsLoaded():null},i.getDuration=function(){return i.player?i.player.getDuration():null},i.getInternalPlayer=function(e){return void 0===e&&(e="player"),i.player?i.player.getInternalPlayer(e):null},i.renderActivePlayer=function(e){if(!e)return null;var t=i.getActivePlayer(e);return t?z.createElement(gc,w(w({},i.props),{key:t.key,ref:i.references.player,activePlayer:t.lazyPlayer||t,onReady:i.handleReady})):null},i}return R(i,r),i.prototype.render=function(){var e=this.props,t=e.src,r=e.style,i=e.width,n=e.height,a=e.fallback,s=e.wrapper,o=this.getAttributes(t),l="string"==typeof s?this.references.wrapper:void 0;return z.createElement(s,w({ref:l,style:w(w({},r),{width:i,height:n})},o),z.createElement(yc,{fallback:a},this.renderActivePlayer(t)))},i}(q.Component),r.displayName="StormcloudPlayer",r.defaultProps=w(w({},Qu),{fallback:null,wrapper:"div"}),r.addCustomPlayer=function(e){kc.push(e)},r.removeCustomPlayers=function(){kc.length=0},r.canPlay=function(t){var r,i;try{for(var n=C(M(M([],_(kc),!1),_(e),!1)),a=n.next();!a.done;a=n.next()){if(a.value.canPlay(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r.canEnablePIP=function(t){var r,i;try{for(var n=C(M(M([],_(kc),!1),_(e),!1)),a=n.next();!a.done;a=n.next()){var s=a.value;if(s.canEnablePIP&&s.canEnablePIP(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r},Sc=Tc(vc,vc[vc.length-1]),bc=null;function Ac(){var e,t,r,i,n,a=navigator.userAgent,s=navigator.platform,o=navigator.vendor||"",l=navigator.maxTouchPoints||0,u=navigator.deviceMemory||null,c=navigator.hardwareConcurrency||1,d={width:null===screen||void 0===screen?void 0:screen.width,height:null===screen||void 0===screen?void 0:screen.height,availWidth:null===screen||void 0===screen?void 0:screen.availWidth,availHeight:null===screen||void 0===screen?void 0:screen.availHeight,orientation:(null===(e=null===screen||void 0===screen?void 0:screen.orientation)||void 0===e?void 0:e.type)||"",pixelDepth:null===screen||void 0===screen?void 0:screen.pixelDepth},h="desktop",f="Unknown",v="Unknown",g="",p=!1,m=!1,y=!1;if(a.includes("Web0S")){f="LG",v="webOS",p=!0,h="tv";var E=a.match(/Web0S\/([^\s]+)/);g=E?"webOS ".concat(E[1]):"webOS TV"}else if(a.includes("Tizen")){f="Samsung",v="Tizen",p=!0,h="tv";var k=a.match(/Tizen\/([^\s]+)/),T=a.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=k?"Tizen ".concat(k[1]," ").concat(T).trim():"Tizen TV"}else a.includes("Philips")?(f="Philips",v="Saphi",p=!0,h="tv"):a.includes("Sharp")||a.includes("AQUOS")?(f="Sharp",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("Sony")||o.includes("Sony"))?(f="Sony",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("NetCast")||a.includes("LG"))?(f="LG",v="Android TV",p=!0,h="tv"):a.includes(" Roku")||a.includes("Roku/")?(f="Roku",v="Roku OS",p=!0,h="tv"):a.includes("AppleTV")&&(f="Apple",v="tvOS",p=!0,h="tv");if(a.includes("Android")){m=!0,v="Android",h=/Mobile/.test(a)?"mobile":"tablet",a.includes("Android")&&(0===l||a.includes("Google TV")||a.includes("XiaoMi"))&&(h="tv",p=!0,f="Unknown"===f?"Android TV":f);var S=a.match(/\(([^)]*Android[^)]*)\)/);S&&S[1]&&(g=S[1])}return/iPad|iPhone|iPod/.test(a)&&(v="iOS",h="mobile",f="Apple",navigator.maxTouchPoints>1&&/iPad/.test(a)&&(h="tablet")),m||p||/Mobile/.test(a)||(a.includes("Windows")?(v="Windows",h="desktop"):a.includes("Mac")&&!/iPhone/.test(a)?(v="macOS",h="desktop",l>1&&(h="tablet")):a.includes("Linux")&&(v="Linux",h="desktop")),"Unknown"===f&&((o.includes("Google")||a.includes("Chrome"))&&(f="Google"),o.includes("Apple")&&(f="Apple"),(o.includes("Samsung")||a.includes("SM-"))&&(f="Samsung")),y=/wv|WebView|Linux; U;/.test(a),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),n=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(r=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===r?void 0:r.angle),{brand:f,os:v,model:g||a.substring(0,50)+"...",deviceType:h,isSmartTV:p,isAndroid:m,isWebView:y,isWebApp:n,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:a,vendor:o,platform:s,screen:d,hardwareConcurrency:c,deviceMemory:u,maxTouchPoints:l,language:navigator.language,languages:(null===(i=navigator.languages)||void 0===i?void 0:i.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function Lc(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u,c,d,h,f;return D(this,function(v){switch(v.label){case 0:if(bc)return[2,bc];if(t=JSON.stringify(e),"undefined"==typeof crypto||!crypto.subtle||!crypto.subtle.digest)return[3,5];v.label=1;case 1:return v.trys.push([1,4,,5]),[4,crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3]))];case 2:if(v.sent(),r=void 0,"undefined"!=typeof TextEncoder)r=(new TextEncoder).encode(t);else{for(i=unescape(encodeURIComponent(t)),n=new Uint8Array(i.length),u=0;u<i.length;u++)n[u]=i.charCodeAt(u);r=n}return[4,crypto.subtle.digest("SHA-256",r)];case 3:return a=v.sent(),s=Array.from(new Uint8Array(a)),o=s.map(function(e){return e.toString(16).padStart(2,"0")}).join(""),bc=o,[2,o];case 4:return v.sent(),console.warn("[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash"),[3,5];case 5:for(l=0,u=0;u<t.length;u++)c=t.charCodeAt(u),l=(l<<5)-l+c,l&=l;return d=Math.abs(l).toString(16).padStart(8,"0"),h=Date.now().toString(16).padStart(12,"0"),f=Math.random().toString(16).substring(2,14).padStart(12,"0"),[2,bc=(d+h+f).padEnd(64,"0")]}})})}var Ic=[".flv",".f4v",".swf",".wmv",".avi",".mov",".mkv",".mp4",".webm"];function Rc(e){try{var t=new URL(e,"http://dummy").pathname;return-1===(r=t.lastIndexOf("."))?"":t.slice(r).toLowerCase()}catch(t){var r;return-1===(r=e.lastIndexOf("."))?"":(e.slice(r).split(/[?#]/)[0]||"").toLowerCase()}}e.IS_BROWSER=rc,e.IS_GLOBAL=ic,e.IS_IOS=nc,e.IS_SAFARI=ac,e.SUPPORTS_DASH=function(){if(!rc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!rc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=Sc,e.StormcloudVideoPlayer=Ru,e.StormcloudVideoPlayerComponent=zu,e.canPlay=dc,e.createAdStormPlayer=Su,e.createHlsAdPlayer=function(e,t){var r,i,n,a,s,o=!1,l=!1,u=Math.max(0,Math.min(1,e.volume||1)),c=new Map,d=null==t?void 0:t.licenseKey,h=null==t?void 0:t.mainHlsInstance,f=!1,v=[],g={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function p(e,t){var r,i,n=c.get(e);if(n)try{for(var a=C(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("[HlsAdPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function m(e){e&&0!==e.length&&e.forEach(function(e){try{var t=e;s&&(t="".concat(t).concat(t.includes("?")?"&":"?","session_id=").concat(s)),d&&(t="".concat(t).concat(t.includes("?")?"&":"?","license_key=").concat(d)),new Image(1,1).src=t,console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(t))}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}function y(e){if(0===e.length)throw new Error("No media files available");var t=e[0];if(!t)throw new Error("No media files available");if(1===e.length)return t;var r=function(){if(!h||!h.levels)return null;var e=h.currentLevel;if(-1===e||!h.levels[e]){var t=h.loadLevel;if(-1!==t&&h.levels[t]){var r=h.levels[t];return{width:r.width||1920,height:r.height||1080,bitrate:r.bitrate||5e6}}return null}var i=h.levels[e];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}();if(!r)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",r);var i=e.map(function(e){var t=Math.abs(e.width-r.width)+Math.abs(e.height-r.height),i=1e3*(e.bitrate||5e3),n=Math.abs(i-r.bitrate);return{file:e,score:2*t+n/1e3,resolutionDiff:t,bitrateDiff:n}});i.sort(function(e,t){return e.score-t.score});var n=i[0];return n?(console.log("[HlsAdPlayer] Selected media file:",{url:n.file.url,resolution:"".concat(n.file.width,"x").concat(n.file.height),bitrate:n.file.bitrate,score:n.score,resolutionDiff:n.resolutionDiff,bitrateDiff:n.bitrateDiff}),n.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}function E(e){var t,r,i,n;try{var a=(new DOMParser).parseFromString(e,"text/xml"),s=a.querySelector("parsererror");if(s)return console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",s.textContent),null;var o=a.querySelector("Ad");if(!o)return console.warn("[HlsAdPlayer] No Ad element found in VAST XML"),null;var l=o.getAttribute("id")||"unknown",u=(null===(t=a.querySelector("AdTitle"))||void 0===t?void 0:t.textContent)||"Ad",c="empty"===l||u.toLowerCase().includes("no ad available")||"no ad available"===u.toLowerCase(),d=((null===(r=a.querySelector("Duration"))||void 0===r?void 0:r.textContent)||"00:00:30").split(":"),h=3600*parseInt(d[0]||"0",10)+60*parseInt(d[1]||"0",10)+parseInt(d[2]||"0",10),f=a.querySelectorAll("MediaFile"),v=[];if(console.log("[HlsAdPlayer] Found ".concat(f.length," MediaFile element(s) in VAST XML")),f.forEach(function(e,t){var r,i=e.getAttribute("type")||"",n=(null===(r=e.textContent)||void 0===r?void 0:r.trim())||"",a=e.getAttribute("width")||"",s=e.getAttribute("height")||"";console.log("[HlsAdPlayer] MediaFile ".concat(t,': type="').concat(i,'", url="').concat(n,'", width="').concat(a,'", height="').concat(s,'"'));var o=n;if((n=function(e){return".flv"===Rc(e)?e.replace(/\.flv(\?|$)/i,".mp4$1"):e}(n))!==o&&console.log("[HlsAdPlayer] Converted FLV to MP4: ".concat(o," -> ").concat(n)),function(e){var t=Rc(e);return-1!==Ic.indexOf(t)}(n)){var l=Rc(n);console.log("[HlsAdPlayer] MediaFile ".concat(t," ignored: unsupported format (extension: ").concat(l,", declared type: ").concat(i,")"))}else if("application/x-mpegURL"===i||i.includes("m3u8")){if(!n)return void console.warn("[HlsAdPlayer] MediaFile ".concat(t," has HLS type but empty URL"));var u=e.getAttribute("bitrate"),c=u?parseInt(u,10):void 0;v.push({url:n,type:i,width:parseInt(a||"1920",10),height:parseInt(s||"1080",10),bitrate:c&&c>0?c:void 0}),console.log("[HlsAdPlayer] Added HLS MediaFile: ".concat(n))}else console.log("[HlsAdPlayer] MediaFile ".concat(t,' ignored (type="').concat(i,'" is not HLS)'))}),0===v.length)return c?console.warn("[HlsAdPlayer] No ads available (VAST response indicates no ads)"):console.warn("[HlsAdPlayer] No HLS media files found in VAST XML"),null;var g={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};a.querySelectorAll("Impression").forEach(function(e){var t,r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&g.impression.push(r)}),a.querySelectorAll("Tracking").forEach(function(e){var t,r=e.getAttribute("event"),i=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(r&&i){var n=r;g[n]&&g[n].push(i)}});var p=null===(n=null===(i=a.querySelector("ClickThrough"))||void 0===i?void 0:i.textContent)||void 0===n?void 0:n.trim();return{id:l,title:u,duration:h,mediaFiles:v,trackingUrls:g,clickThrough:p}}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),null}}function k(e){return x(this,void 0,void 0,function(){var t,r;return D(this,function(i){switch(i.label){case 0:return[4,fetch(e)];case 1:if(!(t=i.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(t.statusText));return[4,t.text()];case 2:return r=i.sent(),console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",r.substring(0,2e3)),[2,E(r)]}})})}function T(){r&&a&&(r.addEventListener("timeupdate",function(){if(a&&r){var e=r.currentTime/a.duration;e>=.25&&!g.firstQuartile&&(g.firstQuartile=!0,m(a.trackingUrls.firstQuartile)),e>=.5&&!g.midpoint&&(g.midpoint=!0,m(a.trackingUrls.midpoint)),e>=.75&&!g.thirdQuartile&&(g.thirdQuartile=!0,m(a.trackingUrls.thirdQuartile))}}),r.addEventListener("playing",function(){a&&!g.start&&(g.start=!0,m(a.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing"))}),r.addEventListener("ended",function(){a&&!g.complete&&(g.complete=!0,m(a.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),function(){console.log("[HlsAdPlayer] Handling ad completion"),o=!1,S(!1),p("content_resume");var t=window.setTimeout(function(){if(f)console.log("[HlsAdPlayer] Player destroyed, skipping post-completion check");else{"true"===e.dataset.stormcloudAdPlaying&&(console.log("[HlsAdPlayer] Still in ad pod - keeping ad container visible (black screen)"),n&&(n.style.display="flex",n.style.pointerEvents="auto"));var r=v.indexOf(t);-1!==r&&v.splice(r,1)}},50);v.push(t)}())}),r.addEventListener("error",function(e){console.error("[HlsAdPlayer] Ad video error:",e),a&&m(a.trackingUrls.error),b()}),r.addEventListener("volumechange",function(){a&&(r.muted?m(a.trackingUrls.mute):m(a.trackingUrls.unmute))}),r.addEventListener("pause",function(){a&&!r.ended&&m(a.trackingUrls.pause)}),r.addEventListener("play",function(){a&&r.currentTime>0&&m(a.trackingUrls.resume)}))}function S(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function b(){console.log("[HlsAdPlayer] Handling ad error"),o=!1,S(!1);var r=e.muted;e.muted=l,e.volume=l?0:u,console.log("[HlsAdPlayer] Restored mute state: ".concat(r," -> ").concat(l)),n&&(n.style.display="none",n.style.pointerEvents="none"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),p("ad_error")}return{initialize:function(){var t;if(console.log("[HlsAdPlayer] Initializing"),!n){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),n=r}},requestAds:function(t){return x(this,void 0,void 0,function(){var r,i,n,l,u;return D(this,function(c){switch(c.label){case 0:if(console.log("[HlsAdPlayer] Requesting ads for duration:",t),o)return console.warn("[HlsAdPlayer] Cannot request new ads while an ad is playing"),[2,Promise.reject(new Error("Ad already playing"))];c.label=1;case 1:return c.trys.push([1,3,,4]),s="session-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),r=30,i=parseInt(t,10),!isNaN(i)&&i>0&&(r=i),n=function(t){var r="https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(d,"/pod"),i={video:{codec:"h264",width:e.videoWidth||1280,height:e.videoHeight||720,fps:29.97,bitrate:5e3,profile:"high",pix_fmt:"yuv420p",has_b_frames:0},audio:{codec:"aac",sample_rate:48e3,bitrate:128}},n=encodeURIComponent(JSON.stringify(i));return"".concat(r,"?duration=").concat(Math.ceil(t),"&metadata=").concat(n)}(r),[4,k(n)];case 2:return(l=c.sent())?(a=l,console.log("[HlsAdPlayer] Ad parsed: ".concat(l.title,", duration: ").concat(l.duration,"s")),m(l.trackingUrls.impression),g.impression=!0,[2,Promise.resolve()]):(console.warn("[HlsAdPlayer] No ads available from VAST response"),p("ad_error"),[2,Promise.resolve()]);case 3:return u=c.sent(),console.error("[HlsAdPlayer] Error requesting ads:",u),p("ad_error"),[2,Promise.reject(u)];case 4:return[2]}})})},play:function(){return x(this,void 0,void 0,function(){var s,c,d;return D(this,function(h){if(!a)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),[2,Promise.reject(new Error("No ad loaded"))];console.log("[HlsAdPlayer] Starting ad playback");try{if(r||((f=document.createElement("video")).style.position="absolute",f.style.left="0",f.style.top="0",f.style.width="100%",f.style.height="100%",f.style.objectFit="contain",f.style.backgroundColor="#000",f.playsInline=!0,f.muted=!1,f.volume=1,console.log("[HlsAdPlayer] Created ad video element with volume ".concat(f.volume)),r=f,null==n||n.appendChild(r),T()),g={impression:g.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},s=e.volume,u=Math.max(0,Math.min(1,s||u)),(null==t?void 0:t.continueLiveStreamDuringAds)?console.log("[HlsAdPlayer] Content continues (Live mode)"):(e.pause(),console.log("[HlsAdPlayer] Content paused (VOD mode)")),console.log("[HlsAdPlayer] FORCE MUTING main video"),e.muted=!0,e.volume=0,o=!0,S(!0),r&&(c=l?0:u,r.volume=Math.max(0,Math.min(1,c)),r.muted=!1,console.log("[HlsAdPlayer] Set ad video volume to ".concat(r.volume,", muted: ").concat(r.muted,", originalMutedState: ").concat(l,", contentVolume: ").concat(s))),n&&(n.style.display="flex",n.style.pointerEvents="auto"),p("content_pause"),!(d=y(a.mediaFiles)))throw new Error("No media file available for ad");if(console.log("[HlsAdPlayer] Loading ad from: ".concat(d.url)),mu.isSupported())i&&i.destroy(),(i=new mu({enableWorker:!0,lowLatencyMode:!1})).loadSource(d.url),i.attachMedia(r),i.on(mu.Events.MANIFEST_PARSED,function(){console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),r.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),b()})}),i.on(mu.Events.ERROR,function(e,t){console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&b()});else{if(!r.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS not supported");r.src=d.url,r.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),b()})}return[2,Promise.resolve()]}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),b(),[2,Promise.reject(e)]}var f;return[2]})})},stop:function(){return x(this,void 0,void 0,function(){return D(this,function(e){return console.log("[HlsAdPlayer] Stopping ad"),o=!1,S(!1),n&&(n.style.display="none",n.style.pointerEvents="none"),i&&(i.destroy(),i=void 0),r&&(r.pause(),r.src=""),a=void 0,[2]})})},destroy:function(){var t,s;console.log("[HlsAdPlayer] Destroying"),f=!0;try{for(var d=C(v),h=d.next();!h.done;h=d.next()){var g=h.value;clearTimeout(g)}}catch(e){t={error:e}}finally{try{h&&!h.done&&(s=d.return)&&s.call(d)}finally{if(t)throw t.error}}v=[],o=!1,S(!1),e.muted=l,e.volume=l?0:u,i&&(i.destroy(),i=void 0),r&&(r.pause(),r.src="",r.remove(),r=void 0),(null==n?void 0:n.parentElement)&&n.parentElement.removeChild(n),n=void 0,a=void 0,c.clear()},isAdPlaying:function(){return o},resize:function(e,t){console.log("[HlsAdPlayer] Resizing to ".concat(e,"x").concat(t)),n&&(n.style.width="".concat(e,"px"),n.style.height="".concat(t,"px")),r&&(r.style.width="".concat(e,"px"),r.style.height="".concat(t,"px"))},on:function(e,t){c.has(e)||c.set(e,new Set),c.get(e).add(t)},off:function(e,t){var r;null===(r=c.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?u:Math.max(0,Math.min(1,t));console.log("[HlsAdPlayer] updateOriginalMutedState called: { muted: ".concat(l," -> ").concat(e,", volume: ").concat(u," -> ").concat(r," }")),l=e,u=r},getOriginalMutedState:function(){return l},getOriginalVolume:function(){return u},setAdVolume:function(e){r&&o&&(r.volume=Math.max(0,Math.min(1,e)))},getAdVolume:function(){return r&&o?r.volume:1},showPlaceholder:function(){var t;if(!n){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),n=r}n&&(n.style.display="flex",n.style.pointerEvents="auto")},hidePlaceholder:function(){n&&(n.style.display="none",n.style.pointerEvents="none")}}},e.createStormcloudPlayer=Tc,e.default=zu,e.detectBrowser=Au,e.getBrowserConfigOverrides=Iu,e.getBrowserID=Lc,e.getClientInfo=Ac,e.initializePolyfills=bu,e.isMediaStream=Zu,e.lazy=$u,e.logBrowserInfo=Lu,e.merge=ec,e.omit=Ju,e.parseQuery=function(e){var t={},r=e.split("?")[1]||"";if(!r)return t;var i=function(e){e.split("&").forEach(function(e){var r=_(e.split("="),2),i=r[0],n=r[1];if(i)try{t[decodeURIComponent(i)]=n?decodeURIComponent(n.replace(/\+/g," ")):""}catch(e){t[i]=n||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(r).forEach(function(e,r){t[r]=e}),t}catch(e){i(r)}else i(r);return t},e.players=vc,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.sendHeartbeat=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a;return D(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),[4,Lc(Ac())];case 1:return t=s.sent(),r={browserId:t,timestamp:(new Date).toISOString()},i={"Content-Type":"application/json"},e&&(i.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:i,body:JSON.stringify(r)})];case 2:if(!(n=s.sent()).ok)throw new Error("HTTP error! status: ".concat(n.status));return[4,n.json()];case 3:return s.sent(),[3,5];case 4:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending heartbeat:",a),[3,5];case 5:return[2]}})})},e.sendInitialTracking=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s;return D(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),[4,Lc(t=Ac())];case 1:return r=o.sent(),i=w({browserId:r},t),n={"Content-Type":"application/json"},e&&(n.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track",{method:"POST",headers:n,body:JSON.stringify(i)})];case 2:if(!(a=o.sent()).ok)throw new Error("HTTP error! status: ".concat(a.status));return[4,a.json()];case 3:return o.sent(),[3,5];case 4:return s=o.sent(),console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",s),[3,5];case 5:return[2]}})})},e.supportsFeature=function(e){switch(e){case"urlsearchparams":return"undefined"!=typeof URLSearchParams;case"textencoder":return"undefined"!=typeof TextEncoder;case"promises":return"undefined"!=typeof Promise;case"fetch":return"undefined"!=typeof fetch;case"crypto":return"undefined"!=typeof crypto&&void 0!==crypto.subtle;default:return!1}},e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=function(){return"undefined"!=typeof window&&"webkitSupportsPresentationMode"in document.createElement("video")},Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StormcloudVP={})}(this,function(e){"use strict";function t(e,t){this.v=e,this.k=t}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function i(e){if(Array.isArray(e))return e}function n(e,t,r){return t=c(t),g(e,h()?Reflect.construct(t,r||[],c(e).constructor):t.apply(e,r))}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,T(i.key),i)}}function o(e,t,r){return t&&s(e.prototype,t),r&&s(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(e,t,r){return(t=T(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(){return u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var i=y(e,t);if(i){var n=Object.getOwnPropertyDescriptor(i,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}},u.apply(null,arguments)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function d(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&p(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(h=function(){return!!e})()}function f(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function v(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function g(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function m(e,t){return i(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var i,n,a,s,o=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;l=!1}else for(;!(l=(i=a.call(r)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}(e,t)||b(e,t)||v()}function y(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=c(e)););return e}function E(e,t,r,i){var n=u(c(1&i?e.prototype:e),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}function k(e){return function(e){if(Array.isArray(e))return r(e)}(e)||f(e)||b(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function T(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");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+""}function S(e){return S="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},S(e)}function b(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}function A(e){var r,i;function n(r,i){try{var s=e[r](i),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var i="return"===r?"return":"next";if(!o.k||t.done)return n(i,t);t=e[i](t).value}a(s.done?"return":"normal",t)},function(e){n("throw",e)})}catch(e){a("throw",e)}}function a(e,t){switch(e){case"return":r.resolve({value:t,done:!0});break;case"throw":r.reject(t);break;default:r.resolve({value:t,done:!1})}(r=r.next)?n(r.key,r.arg):i=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};i?i=i.next=o:(r=i=o,n(e,t))})},"function"!=typeof e.return&&(this.return=void 0)}function L(e){var t="function"==typeof Map?new Map:void 0;return L=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&p(n,r.prototype),n}(e,arguments,c(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),p(r,e)},L(e)}A.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},A.prototype.next=function(e){return this._invoke("next",e)},A.prototype.throw=function(e){return this._invoke("throw",e)},A.prototype.return=function(e){return this._invoke("return",e)};var I=function(e,t){return I=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},I(e,t)};function R(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}I(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var w=function(){return w=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},w.apply(this,arguments)};function P(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function x(e,t,r,i){return new(r||(r=Promise))(function(n,a){function s(e){try{l(i.next(e))}catch(e){a(e)}}function o(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((i=i.apply(e,t||[])).next())})}function D(e,t){var r,i,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(r=1,i&&(n=2&o[0]?i.return:o[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,o[1])).done)return n;switch(i=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,i=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){a.label=o[1];break}if(6===o[0]&&a.label<n[1]){a.label=n[1],n=o;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(o);break}n[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],i=0}finally{r=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function C(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function _(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,a=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=a.next()).done;)s.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return s}function M(e,t,r){if(r||2===arguments.length)for(var i,n=0,a=t.length;n<a;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}Object.create;"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function O(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var F,N={exports:{}},U={};var B,G={exports:{}},H={};function V(){if(B)return H;B=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),s=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),c=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),h=Symbol.iterator;var f={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,g={};function p(e,t,r){this.props=e,this.context=t,this.refs=g,this.updater=r||f}function m(){}function y(e,t,r){this.props=e,this.context=t,this.refs=g,this.updater=r||f}p.prototype.isReactComponent={},p.prototype.setState=function(e,t){if("object"!==S(e)&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},p.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},m.prototype=p.prototype;var E=y.prototype=new m;E.constructor=y,v(E,p.prototype),E.isPureReactComponent=!0;var k=Array.isArray;function T(){}var b={H:null,A:null,T:null,S:null},A=Object.prototype.hasOwnProperty;function L(t,r,i){var n=i.ref;return{$$typeof:e,type:t,key:r,ref:void 0!==n?n:null,props:i}}function I(t){return"object"===S(t)&&null!==t&&t.$$typeof===e}var R=/\/+/g;function w(e,t){return"object"===S(e)&&null!==e&&null!=e.key?(r=""+e.key,i={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,function(e){return i[e]})):t.toString(36);var r,i}function P(r,i,n,a,s){var o=S(r);"undefined"!==o&&"boolean"!==o||(r=null);var l,u,d=!1;if(null===r)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(r.$$typeof){case e:case t:d=!0;break;case c:return P((d=r._init)(r._payload),i,n,a,s)}}if(d)return s=s(r),d=""===a?"."+w(r,0):a,k(s)?(n="",null!=d&&(n=d.replace(R,"$&/")+"/"),P(s,i,n,"",function(e){return e})):null!=s&&(I(s)&&(l=s,u=n+(null==s.key||r&&r.key===s.key?"":(""+s.key).replace(R,"$&/")+"/")+d,s=L(l.type,u,l.props)),i.push(s)),1;d=0;var f,v=""===a?".":a+":";if(k(r))for(var g=0;g<r.length;g++)d+=P(a=r[g],i,n,o=v+w(a,g),s);else if("function"==typeof(g=null===(f=r)||"object"!==S(f)?null:"function"==typeof(f=h&&f[h]||f["@@iterator"])?f:null))for(r=g.call(r),g=0;!(a=r.next()).done;)d+=P(a=a.value,i,n,o=v+w(a,g++),s);else if("object"===o){if("function"==typeof r.then)return P(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(T,T):(e.status="pending",e.then(function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)},function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(r),i,n,a,s);throw i=String(r),Error("Objects are not valid as a React child (found: "+("[object Object]"===i?"object with keys {"+Object.keys(r).join(", ")+"}":i)+"). If you meant to render a collection of children, use an array instead.")}return d}function x(e,t,r){if(null==e)return e;var i=[],n=0;return P(e,i,"","",function(e){return t.call(r,e,n++)}),i}function D(e){if(-1===e._status){var t=e._result;(t=t()).then(function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)},function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)}),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var C="function"==typeof reportError?reportError:function(e){if("object"===("undefined"==typeof window?"undefined":S(window))&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"===S(e)&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"===("undefined"==typeof process?"undefined":S(process))&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},_={map:x,forEach:function(e,t,r){x(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return x(e,function(){t++}),t},toArray:function(e){return x(e,function(e){return e})||[]},only:function(e){if(!I(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};return H.Activity=d,H.Children=_,H.Component=p,H.Fragment=r,H.Profiler=n,H.PureComponent=y,H.StrictMode=i,H.Suspense=l,H.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=b,H.__COMPILER_RUNTIME={__proto__:null,c:function(e){return b.H.useMemoCache(e)}},H.cache=function(e){return function(){return e.apply(null,arguments)}},H.cacheSignal=function(){return null},H.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var i=v({},e.props),n=e.key;if(null!=t)for(a in void 0!==t.key&&(n=""+t.key),t)!A.call(t,a)||"key"===a||"__self"===a||"__source"===a||"ref"===a&&void 0===t.ref||(i[a]=t[a]);var a=arguments.length-2;if(1===a)i.children=r;else if(1<a){for(var s=Array(a),o=0;o<a;o++)s[o]=arguments[o+2];i.children=s}return L(e.type,n,i)},H.createContext=function(e){return(e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider=e,e.Consumer={$$typeof:a,_context:e},e},H.createElement=function(e,t,r){var i,n={},a=null;if(null!=t)for(i in void 0!==t.key&&(a=""+t.key),t)A.call(t,i)&&"key"!==i&&"__self"!==i&&"__source"!==i&&(n[i]=t[i]);var s=arguments.length-2;if(1===s)n.children=r;else if(1<s){for(var o=Array(s),l=0;l<s;l++)o[l]=arguments[l+2];n.children=o}if(e&&e.defaultProps)for(i in s=e.defaultProps)void 0===n[i]&&(n[i]=s[i]);return L(e,a,n)},H.createRef=function(){return{current:null}},H.forwardRef=function(e){return{$$typeof:o,render:e}},H.isValidElement=I,H.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:D}},H.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},H.startTransition=function(e){var t=b.T,r={};b.T=r;try{var i=e(),n=b.S;null!==n&&n(r,i),"object"===S(i)&&null!==i&&"function"==typeof i.then&&i.then(T,C)}catch(e){C(e)}finally{null!==t&&null!==r.types&&(t.types=r.types),b.T=t}},H.unstable_useCacheRefresh=function(){return b.H.useCacheRefresh()},H.use=function(e){return b.H.use(e)},H.useActionState=function(e,t,r){return b.H.useActionState(e,t,r)},H.useCallback=function(e,t){return b.H.useCallback(e,t)},H.useContext=function(e){return b.H.useContext(e)},H.useDebugValue=function(){},H.useDeferredValue=function(e,t){return b.H.useDeferredValue(e,t)},H.useEffect=function(e,t){return b.H.useEffect(e,t)},H.useEffectEvent=function(e){return b.H.useEffectEvent(e)},H.useId=function(){return b.H.useId()},H.useImperativeHandle=function(e,t,r){return b.H.useImperativeHandle(e,t,r)},H.useInsertionEffect=function(e,t){return b.H.useInsertionEffect(e,t)},H.useLayoutEffect=function(e,t){return b.H.useLayoutEffect(e,t)},H.useMemo=function(e,t){return b.H.useMemo(e,t)},H.useOptimistic=function(e,t){return b.H.useOptimistic(e,t)},H.useReducer=function(e,t,r){return b.H.useReducer(e,t,r)},H.useRef=function(e){return b.H.useRef(e)},H.useState=function(e){return b.H.useState(e)},H.useSyncExternalStore=function(e,t,r){return b.H.useSyncExternalStore(e,t,r)},H.useTransition=function(){return b.H.useTransition()},H.version="19.2.0",H}var K;G.exports;function j(){return K||(K=1,G.exports=V()),G.exports}var Y;N.exports;var W=(Y||(Y=1,N.exports=function(){if(F)return U;F=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(t,r,i){var n=null;if(void 0!==i&&(n=""+i),void 0!==r.key&&(n=""+r.key),"key"in r)for(var a in i={},r)"key"!==a&&(i[a]=r[a]);else i=r;return r=i.ref,{$$typeof:e,type:t,key:n,ref:void 0!==r?r:null,props:i}}return U.Fragment=t,U.jsx=r,U.jsxs=r,U}()),N.exports),q=j(),z=O(q),X=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Q=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=$},$=Number.MAX_SAFE_INTEGER||9007199254740991,J=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}({}),Z=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}({}),ee=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}({}),te="manifest",re="level",ie="audioTrack",ne="subtitleTrack",ae="main",se="audio",oe="subtitle",le=function(){return o(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;a(this,e),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=i},[{key:"sample",value:function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}},{key:"getTotalWeight",value:function(){return this.totalWeight_}},{key:"getEstimate",value:function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}])}(),ue=function(){return o(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;a(this,e),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_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new le(t),this.fast_=new le(r),this.defaultTTFB_=n,this.ttfb_=new le(t)},[{key:"update",value:function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new le(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new le(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new le(e,n.getEstimate(),n.getTotalWeight()))}},{key:"sample",value:function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}},{key:"sampleTTFB",value:function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}},{key:"canEstimate",value:function(){return this.fast_.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"getEstimateTTFB",value:function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{key:"defaultEstimate",get:function(){return this.defaultEstimate_}},{key:"destroy",value:function(){}}])}();function ce(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=S(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=S(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==S(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function de(){return de=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},de.apply(null,arguments)}function he(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function fe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?he(Object(r),!0).forEach(function(t){ce(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):he(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var ve=o(function e(t,r){a(this,e),this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="[".concat(t,"]:");this.trace=ge,this.debug=r.debug.bind(null,i),this.log=r.log.bind(null,i),this.warn=r.warn.bind(null,i),this.info=r.info.bind(null,i),this.error=r.error.bind(null,i)}),ge=function(){},pe={trace:ge,debug:ge,log:ge,warn:ge,info:ge,error:ge};function me(){return de({},pe)}function ye(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):ge}(e,r)}var Ee=me();var ke=Ee;function Te(){if("undefined"!=typeof self)return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0]||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Se(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some(function(e){return-1===i.indexOf(e)})}function be(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if("undefined"!=typeof TextDecoder){var r=new TextDecoder("utf-8").decode(e);if(t){var i=r.indexOf("\0");return-1!==i?r.substring(0,i):r}return r.replace(/\0/g,"")}for(var n,a,s,o=e.length,l="",u=0;u<o;){if(0===(n=e[u++])&&t)return l;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:a=e[u++],l+=String.fromCharCode((31&n)<<6|63&a);break;case 14:a=e[u++],s=e[u++],l+=String.fromCharCode((15&n)<<12|(63&a)<<6|63&s)}}return l}function Ae(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Le(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Ie(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Re,we={exports:{}};var Pe=(Re||(Re=1,function(e){var t,r,i,n,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):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=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(u.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var c=o.path,d=c.substring(0,c.lastIndexOf("/")+1)+s.path;u.path=a.normalizePath(d)}else u.path=o.path,s.params||(u.params=o.params,s.query||(u.query=o.query));return null===u.path&&(u.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(we)),we.exports),xe=o(function e(){a(this,e),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}}),De="audio",Ce="video",_e="audiovideo",Me=function(){return o(function e(t){var r,i,n;a(this,e),this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,(n=Ue(r=this,i="stats"))&&(n.enumerable=!0,Object.defineProperty(r,i,n))},[{key:"setByteRange",value:function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}},{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){return null===this._streams&&(this._streams=l(l(l({},De,null),Ce,null),_e,null)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new xe),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Pe.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}},{key:"clearElementaryStreamInfo",value:function(){var e=this.elementaryStreams;e[De]=null,e[Ce]=null,e[_e]=null}}])}();function Oe(e){return"initSegment"!==e.sn}var Fe=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r]))._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=e,i}return d(t,e),o(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],r=this.byteRange[1];if(X(t)&&X(r))return r-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){var e,t=this.levelkeys;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){var r=Object.keys(t);if(1===r.length){var i=this._decryptdata=t[r[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=X(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,r=Object.keys(this.levelkeys),i=r.length;if(i>1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){X(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return Oe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}},{key:"addStart",value:function(e){this.setStart(this.start+e)}},{key:"setStart",value:function(e){this.start=e,this._ref&&(this._ref.start=e)}},{key:"setDuration",value:function(e){this.duration=e,this._ref&&(this._ref.duration=e)}},{key:"setKeyFormat",value:function(e){var t=this.levelkeys;if(t){var r,i=t[e];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}},{key:"abortRequests",value:function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}},{key:"setElementaryStreamInfo",value:function(e,t,r,i,n){var a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}}}])}(Me),Ne=function(e){function t(e,r,i,s,o){var l;a(this,t),(l=n(this,t,[i])).fragOffset=0,l.duration=0,l.gap=!1,l.independent=!1,l.relurl=void 0,l.fragment=void 0,l.index=void 0,l.duration=e.decimalFloatingPoint("DURATION"),l.gap=e.bool("GAP"),l.independent=e.bool("INDEPENDENT"),l.relurl=e.enumeratedString("URI"),l.fragment=r,l.index=s;var u=e.enumeratedString("BYTERANGE");return u&&l.setByteRange(u,o),o&&(l.fragOffset=o.fragOffset+o.duration),l}return d(t,e),o(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}])}(Me);function Ue(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||Ue(r,t)}}var Be=Math.pow(2,32)-1,Ge=[].push,He={video:1,audio:2,id3:3,text:4};function Ve(e){return String.fromCharCode.apply(null,e)}function Ke(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function je(e,t){var r=We(e,t);return r<0?4294967296+r:r}function Ye(e,t){var r=je(e,t);return r*=Math.pow(2,32),r+=je(e,t+4)}function We(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function qe(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,n=0;n<i;){var a=je(e,n),s=a>1?n+a:i;if(Ve(e.subarray(n+4,n+8))===t[0])if(1===t.length)r.push(e.subarray(n+8,s));else{var o=qe(e.subarray(n+8,s),t.slice(1));o.length&&Ge.apply(r,o)}n=s}return r}function ze(e){var t=[],r=e[0],i=8,n=je(e,i);i+=4;var a=0,s=0;0===r?(a=je(e,i),s=je(e,i+4),i+=8):(a=Ye(e,i),s=Ye(e,i+8),i+=16),i+=2;var o=e.length+s,l=Ke(e,i);i+=2;for(var u=0;u<l;u++){var c=i,d=je(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return ke.warn("SIDX has hierarchical references (not supported)"),null;var f=je(e,c);c+=4,t.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+h-1}}),o+=h,i=c+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function Xe(e){for(var t=[],r=qe(e,["moov","trak"]),i=0;i<r.length;i++){var n=r[i],a=qe(n,["tkhd"])[0];if(a){var s=a[0],o=je(a,0===s?12:20),l=qe(n,["mdia","mdhd"])[0];if(l){var u=je(l,0===(s=l[0])?12:20),c=qe(n,["mdia","hdlr"])[0];if(c){var d=Ve(c.subarray(8,12)),h={soun:De,vide:Ce}[d],f=Qe(qe(n,["mdia","minf","stbl","stsd"])[0]);h?(t[o]={timescale:u,type:h,stsd:f},t[h]=fe({timescale:u,id:o},f)):t[o]={timescale:u,type:d,stsd:f}}}}}return qe(e,["moov","mvex","trex"]).forEach(function(e){var r=je(e,4),i=t[r];i&&(i.default={duration:je(e,12),flags:je(e,20)})}),t}function Qe(e){var t,r=e.subarray(8),i=r.subarray(86),n=Ve(r.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=qe(r,[n])[0];qe(o.subarray("enca"===n?28:78),["sinf"]).forEach(function(e){var t=qe(e,["schm"])[0];if(t){var r=Ve(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=qe(e,["frma"])[0];i&&(a=Ve(i))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=qe(i,["avcC"])[0];u&&u.length>3&&(a+="."+Ze(u[1])+Ze(u[2])+Ze(u[3]),t=$e("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var c=qe(r,[n])[0],d=qe(c.subarray(28),["esds"])[0];if(d&&d.length>7){var h=4;if(3!==d[h++])break;h=Je(d,h),h+=2;var f=d[h++];if(128&f&&(h+=2),64&f&&(h+=d[h++]),4!==d[h++])break;h=Je(d,h);var v=d[h++];if(64!==v)break;if(a+="."+Ze(v),h+=12,5!==d[h++])break;h=Je(d,h);var g=d[h++],p=(248&g)>>3;31===p&&(p+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+p}break;case"hvc1":case"hev1":var m=qe(i,["hvcC"])[0];if(m&&m.length>12){var y=m[1],E=["","A","B","C"][y>>6],k=31&y,T=je(m,2),S=(32&y)>>5?"H":"L",b=m[12],A=m.subarray(6,12);a+="."+E+k,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(T).toString(16).toUpperCase(),a+="."+S+b;for(var L="",I=A.length;I--;){var R=A[I];if(R||L)L="."+R.toString(16).toUpperCase()+L}a+=L}t=$e("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=$e(a,i)||a;break;case"vp09":var w=qe(i,["vpcC"])[0];if(w&&w.length>6){var P=w[4],x=w[5],D=w[6]>>4&15;a+="."+et(P)+"."+et(x)+"."+et(D)}break;case"av01":var C=qe(i,["av1C"])[0];if(C&&C.length>2){var _=C[1]>>>5,M=31&C[1],O=C[2]>>>7?"H":"M",F=(64&C[2])>>6,N=(32&C[2])>>5,U=2===_&&F?N?12:10:F?10:8,B=(16&C[2])>>4,G=(8&C[2])>>3,H=(4&C[2])>>2,V=3&C[2];a+="."+_+"."+et(M)+O+"."+et(U)+"."+B+"."+G+H+V+"."+et(1)+"."+et(1)+"."+et(1)+".0",t=$e("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function $e(e,t){var r=qe(t,["dvvC"]),i=r.length?r[0]:qe(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+et(n)+"."+et(a)}}function Je(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function Ze(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function et(e){return(e<10?"0":"")+e}function tt(e,t){qe(e,["moov","trak"]).forEach(function(e){var r=qe(e,["mdia","minf","stbl","stsd"])[0];if(r){var i=r.subarray(8),n=qe(i,["enca"]),a=n.length>0;a||(n=qe(i,["encv"])),n.forEach(function(e){qe(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var r=rt(e);r&&t(r,a)})})}})}function rt(e){var t=qe(e,["schm"])[0];if(t){var r=Ve(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=qe(e,["schi","tenc"])[0];if(i)return i}}}function it(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function nt(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return qe(i,["moof"]).map(function(o){var l=o.byteOffset-8;qe(o,["traf"]).map(function(o){var u=qe(o,["tfdt"]).map(function(e){var t=e[0],r=je(e,4);return 1===t&&(r*=Math.pow(2,32),r+=je(e,8)),r/n})[0];return void 0!==u&&(e=u),qe(o,["tfhd"]).map(function(u){var c=je(u,4),d=16777215&je(u,0),h=0,f=!!(16&d),v=0,g=!!(32&d),p=8;c===a&&(!!(1&d)&&(p+=8),!!(2&d)&&(p+=4),!!(8&d)&&(h=je(u,p),p+=4),f&&(v=je(u,p),p+=4),g&&(p+=4),"video"===t.type&&(s=at(t.codec)),qe(o,["trun"]).map(function(a){var o=a[0],u=16777215&je(a,0),c=!!(1&u),d=0,f=!!(4&u),g=!!(256&u),p=0,m=!!(512&u),y=0,E=!!(1024&u),k=!!(2048&u),T=0,S=je(a,4),b=8;c&&(d=je(a,b),b+=4),f&&(b+=4);for(var A=d+l,L=0;L<S;L++){if(g?(p=je(a,b),b+=4):p=h,m?(y=je(a,b),b+=4):y=v,E&&(b+=4),k&&(T=0===o?je(a,b):We(a,b),b+=4),t.type===Ce)for(var I=0;I<y;){var R=je(i,A);if(st(s,i[A+=4]))ot(i.subarray(A,A+R),s?2:1,e+T/n,r);A+=R,I+=R+4}e+=p/n}}))})})}),r}function at(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function st(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6===(31&t)}function ot(e,t,r,i){var n=lt(e),a=0;a+=t;for(var s=0,o=0,l=0;a<n.length;){s=0;do{if(a>=n.length)break;s+=l=n[a++]}while(255===l);o=0;do{if(a>=n.length)break;o+=l=n[a++]}while(255===l);var u=n.length-a,c=a;if(o<u)a+=o;else if(o>u){ke.error("Malformed SEI payload. ".concat(o," is too small, only ").concat(u," bytes left to parse."));break}if(4===s){if(181===n[c++]){var d=Ke(n,c);if(c+=2,49===d){var h=je(n,c);if(c+=4,1195456820===h){var f=n[c++];if(3===f){var v=n[c++],g=64&v,p=g?2+3*(31&v):0,m=new Uint8Array(p);if(g){m[0]=v;for(var y=1;y<p;y++)m[y]=n[c++]}i.push({type:f,payloadType:s,pts:r,bytes:m})}}}}}else if(5===s&&o>16){for(var E=[],k=0;k<16;k++){var T=n[c++].toString(16);E.push(1==T.length?"0"+T:T),3!==k&&5!==k&&7!==k&&9!==k||E.push("-")}for(var S=o-16,b=new Uint8Array(S),A=0;A<S;A++)b[A]=n[c++];i.push({payloadType:s,pts:r,uuid:E.join(""),userData:be(b),userDataBytes:b})}}}function lt(e){for(var t=e.byteLength,r=[],i=1;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;var n=t-r.length,a=new Uint8Array(n),s=0;for(i=0;i<n;s++,i++)s===r[0]&&(s++,r.shift()),a[i]=e[s];return a}function ut(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var i,n;i=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=r.length,a=8,s=n;s--;)a+=r[s].byteLength;var o=new Uint8Array(a);for(o[0]=a>>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s<n;s++)o.set(r[s],a),a+=r[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,r)}function ct(e){var t=e.getUint32(0),r=e.byteOffset,i=e.byteLength;if(i<t)return{offset:r,size:i};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a=e.buffer,s=Ae(new Uint8Array(a,r+12,16)),o=null,l=0;if(0===n)l=28;else{var u=e.getUint32(28);if(!u||i<32+16*u)return{offset:r,size:t};o=[];for(var c=0;c<u;c++)o.push(new Uint8Array(a,r+32+16*c,16));l=32+16*u}if(!l)return{offset:r,size:t};var d=e.getUint32(l);return t-32<d?{offset:r,size:t}:{version:n,systemId:s,kids:o,data:new Uint8Array(a,r+l+4,d),offset:r,size:t}}var dt=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},ht={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 ft(e,t){var r=ht[t];return!!r&&!!r[e.slice(0,4)]}function vt(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!gt(e,t,r)})}function gt(e,t){var r,i=Te(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(r=null==i?void 0:i.isTypeSupported(pt(e,t)))&&r}function pt(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function mt(e){if(e){var t=e.substring(0,4);return ht.video[t]}return 2}function yt(e){var t=dt();return e.split(",").reduce(function(e,r){var i=t&&at(r)?9:ht.video[r];return i?(2*i+e)/(e?3:2):(ht.audio[r]+e)/(e?2:1)},0)}var Et={};var kt=/flac|opus|mp4a\.40\.34/i;function Tt(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(kt,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(Et[e])return Et[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var n;if(gt(r[i],"audio",t))return Et[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=Te(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)})}function St(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(bt(e,"audio")||bt(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function bt(e,t){return ft(e,t)&&gt(e,t)}function At(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function Lt(e){var t=Te(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function It(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Rt={supported:!1,smooth:!1,powerEfficient:!1},wt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Pt(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Rt],error:e}}function xt(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve(wt);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=Ct(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(function(e){var t={contentType:pt(At(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=Ct(e);if(n&&e.audioGroups)return e.audioGroups.reduce(function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach(function(t){var i={contentType:pt(t,"audio"),bitrate:r?Dt(t,a):a};s&&(i.channels=""+s),e.push(i)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length,c=o||1*u||1;c--;){var d={type:"media-source"};if(o&&(d.video=s[c%o]),u){d.audio=l[c%u];var h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}a.push(d)}if(n){var f=navigator.userAgent;if(n.split(",").some(function(e){return at(e)})&&dt())return Promise.resolve(Pt(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (".concat(f,")")),a))}return Promise.all(a.map(function(e){var t=function(e){var t="",r=e.audio,i=e.video;if(i){var n=It(i.contentType);t+="".concat(n,"_r").concat(i.height,"x").concat(i.width,"f").concat(Math.ceil(i.framerate)).concat(i.transferFunction||"sd","_").concat(Math.ceil(i.bitrate/1e5))}if(r){var a=It(r.contentType);t+="".concat(i?"_":"").concat(a,"_c").concat(r.channels)}return t}(e);return i[t]||(i[t]=r.decodingInfo(e))})).then(function(e){return{supported:!e.some(function(e){return!e.supported}),configurations:a,decodingInfoResults:e}}).catch(function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}})}function Dt(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function Ct(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var _t=["NONE","TYPE-0","TYPE-1",null];var Mt=["SDR","PQ","HLG"];var Ot="",Ft="YES",Nt="v2";function Ut(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?Nt:Ft:Ot}var Bt=function(){return o(function e(t,r,i){a(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=i},[{key:"addDirectives",value:function(e){var 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}}])}(),Gt=function(){return o(function e(t){if(a(this,e),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=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;var i=null==(r=t.supplemental)?void 0:r.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=",".concat(i.substring(0,4)))}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)},[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"hasAudioGroup",value:function(e){return Ht(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return Ht(this._subtitleGroups,e)}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"addGroupId",value:function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}},{key:"addFallback",value:function(){}}])}();function Ht(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Vt(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var n="SDR"!==(i=t.allowedVideoRanges||Mt.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}var Kt=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"===S(i)&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function jt(e,t){ke.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function Yt(e){return e.reduce(function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Wt(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function qt(e,t,r){if("attrs"in e){var i=t.indexOf(e);if(-1!==i)return i}for(var n=0;n<t.length;n++){if(zt(e,t[n],r))return n}return-1}function zt(e,t,r){var i=e.groupId,n=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===n||t.name===n)&&(void 0===a||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===a||t.assocLang===s)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=e.split(","),i=t.split(",");return r.length===i.length&&!r.some(function(e){return-1===i.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Xt(e,t){var r=e.audioCodec,i=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function Qt(e,t,r){for(var i=t;i>-1;i--)if(r(e[i]))return i;for(var n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function $t(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}var Jt=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["abr",e.logger])).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,n=i.fragCurrent,a=i.partCurrent,s=i.hls,o=s.autoLevelEnabled,l=s.media;if(n&&l){var u=performance.now(),c=a?a.stats:n.stats,d=a?a.duration:n.duration,h=u-c.loading.start,f=s.minAutoLevel,v=n.level,g=r._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var p=g>-1&&g!==v,m=!!e||p;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(m||null!==y){var E=r.bwEstimator.getEstimateTTFB(),k=Math.abs(l.playbackRate);if(!(h<=Math.max(E,d/(2*k)*1e3))){var T=y?y.len/k:0,S=c.loading.first?c.loading.first-c.loading.start:-1,b=c.loaded&&S>-1,A=r.getBwEstimate(),L=s.levels,I=L[v],R=Math.max(c.loaded,Math.round(d*(n.bitrate||I.averageBitrate)/8)),w=b?h-S:h;w<1&&b&&(w=Math.min(h,8*c.loaded/A));var P=b?1e3*c.loaded/w:0,x=E/1e3,D=P?(R-c.loaded)/P:8*R/A+x;if(!(D<=T)){var C,_=P?8*P:A,M=!0===(null==(t=(null==e?void 0:e.details)||r.hls.latestLevelDetails)?void 0:t.live),O=r.hls.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(C=v-1;C>f;C--){var N=L[C].maxBitrate,U=!L[C].details||M;if((F=r.getTimeToLoadFrag(x,_,d*N,U))<Math.min(T,d+x))break}if(!(F>=D||F>10*d)){b?r.bwEstimator.sample(h-Math.min(E,S),c.loaded):r.bwEstimator.sampleTTFB(h);var B=L[C].maxBitrate;r.getBwEstimate()*O>B&&r.resetEstimator(B);var G=r.findBestLevel(B,f,C,0,T,1,1);G>-1&&(C=G),r.warn("Fragment ".concat(n.sn).concat(a?" part "+a.index:""," of level ").concat(v," is loading too slowly;\n Fragment duration: ").concat(n.duration.toFixed(3),"\n Time to underbuffer: ").concat(T.toFixed(3)," s\n Estimated load time for current fragment: ").concat(D.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(F.toFixed(3)," s\n TTFB estimate: ").concat(0|S," ms\n Current BW estimate: ").concat(X(A)?0|A:"Unknown"," bps\n New BW estimate: ").concat(0|r.getBwEstimate()," bps\n Switching to level ").concat(C," @ ").concat(0|B," bps")),s.nextLoadLevel=s.nextAutoLevel=C,r.clearTimer();var H=function(){if(r.clearTimer(),r.fragCurrent===n&&r.hls.loadLevel===C&&C>0){var e=r.getStarvationDelay();if(r.warn("Aborting inflight request ".concat(C>0?"and switching down":"","\n Fragment duration: ").concat(n.duration.toFixed(3)," s\n Time to underbuffer: ").concat(e.toFixed(3)," s")),n.abortRequests(),r.fragCurrent=r.partCurrent=null,C>f){var t=r.findBestLevel(r.hls.levels[f].bitrate,f,C,0,e,1,1);-1===t&&(t=f),r.hls.nextLoadLevel=r.hls.nextAutoLevel=t,r.resetEstimator(r.hls.levels[t].bitrate)}}};p||D>2*F?H():r.timer=self.setInterval(H,1e3*F),s.trigger(ee.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:c})}}}}}}}},r.hls=e,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}return d(t,e),o(t,[{key:"resetEstimator",value:function(e){e&&(this.log("setting initial bwe to ".concat(e)),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}},{key:"initEstimator",value:function(){var e=this.hls.config;return new ue(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.FRAG_LOADING,this.onFragLoading,this),e.on(ee.FRAG_LOADED,this.onFragLoaded,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(ee.ERROR,this.onError,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}},{key:"onManifestLoading",value:function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}},{key:"onLevelsUpdated",value:function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}},{key:"onMaxAutoLevelUpdated",value:function(){this.firstSelection=-1,this.nextAutoLevelKey=""}},{key:"onFragLoading",value:function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}},{key:"onLevelSwitching",value:function(e,t){this.clearTimer()}},{key:"onError",value:function(e,t){if(!t.fatal)switch(t.details){case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Z.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}}},{key:"getTimeToLoadFrag",value:function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;X(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var r=t.frag,i=t.part,n=i?i.stats:r.stats;if(r.type===ae&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var a=i?i.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+n.loaded,l=(s.loaded?s.loaded.duration:0)+a;s.loaded={bytes:o,duration:l},s.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var u={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(ee.FRAG_BUFFERED,u),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}}},{key:"ignoreFragment",value:function(e){return e.type!==ae||"initSegment"===e.sn}},{key:"clearTimer",value:function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}},{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(i,r,t,0,n,1,1);if(a>-1)return a;var s=this.hls.firstLevel,o=Math.min(Math.max(s,r),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(s," clamped to ").concat(o)),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}},{key:"getAutoLevelKey",value:function(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}},{key:"getNextABRAutoLevel",value:function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,i,l,0,u,c);if(d>=0)return this.rebufferNotice=-1,d}var h=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;if(f)h=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-f,this.info("bitrate test took ".concat(Math.round(1e3*f),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*h)," ms")),u=c=1}var v=this.findBestLevel(o,a,i,l,h,u,c);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info("".concat(l?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(v))),v>-1)return v;var g=r.levels[a],p=r.loadLevelObj;return p&&(null==g?void 0:g.bitrate)<p.bitrate?a:r.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}},{key:"getBwEstimate",value:function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}},{key:"findBestLevel",value:function(e,t,r,i,n,a,s){var o,l=this,u=i+n,c=this.lastLoadedFragLevel,d=-1===c?this.hls.firstLevel:c,h=this.fragCurrent,f=this.partCurrent,v=this.hls,g=v.levels,p=v.allAudioTracks,m=v.loadLevel,y=v.config;if(1===g.length)return 0;var E,k=g[d],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),S=-1===m||-1===c,b="SDR",A=(null==k?void 0:k.frameRate)||0,L=y.audioPreference,I=y.videoPreference,R=this.audioTracksByGroup||(this.audioTracksByGroup=Yt(p)),w=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;var P=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce(function(e,r,i){if(!r.codecSet)return e;var n=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.minIndex=Math.min(a.minIndex,i),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,n&&n.forEach(function(e){if(e){var r=t.groups[e];r&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]}))}}),e},{})}(g,R,t,r)),x=function(e,t,r,i,n){for(var a=Object.keys(e),s=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==n?void 0:n.videoCodec,u=s&&2===parseInt(s),c=!1,d=!1,h=1/0,f=1/0,v=1/0,g=1/0,p=0,m=[],y=Vt(t,n),E=y.preferHDR,k=y.allowedVideoRanges,T=function(){var t=e[a[S]];c||(c=t.channels[2]>0),h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),v=Math.min(v,t.minBitrate),k.filter(function(e){return t.videoRanges[e]>0}).length>0&&(d=!0)},S=a.length;S--;)T();h=X(h)?h:0,f=X(f)?f:0;var b=Math.max(1080,h),A=Math.max(30,f);v=X(v)?v:r,r=Math.max(v,r),d||(t=void 0);var L=a.length>1;return{codecSet:a.reduce(function(t,i){var n=e[i];if(i===t)return t;if(m=d?k.filter(function(e){return n.videoRanges[e]>0}):[],L){if(n.minBitrate>r)return jt(i,"min bitrate of ".concat(n.minBitrate," > current estimate of ").concat(r)),t;if(!n.hasDefaultAudio)return jt(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return jt(i,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!n.channels[s])return jt(i,"no renditions with ".concat(s," channel sound found (channels options: ").concat(Object.keys(n.channels),")")),t}else if((!o||u)&&c&&0===n.channels[2])return jt(i,"no renditions with stereo sound found"),t;if(n.minHeight>b)return jt(i,"min resolution of ".concat(n.minHeight," > maximum of ").concat(b)),t;if(n.minFramerate>A)return jt(i,"min framerate of ".concat(n.minFramerate," > maximum of ").concat(A)),t;if(!m.some(function(e){return n.videoRanges[e]>0}))return jt(i,"no variants with VIDEO-RANGE of ".concat(Kt(m)," found")),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return jt(i,'video codec preference "'.concat(l,'" not found')),t;if(n.maxScore<p)return jt(i,"max score of ".concat(n.maxScore," < selected max of ").concat(p)),t}return t&&(yt(i)>=yt(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,p=n.maxScore,i)},void 0),videoRanges:m,preferHDR:E,minFramerate:f,minBitrate:v,minIndex:g}}(P,b,e,L,I),D=x.codecSet,C=x.videoRanges,_=x.minFramerate,M=x.minBitrate,O=x.minIndex,F=x.preferHDR;w=O,E=D,b=F?C[C.length-1]:C[0],A=_,e=Math.max(e,M),this.log("picked start tier ".concat(Kt(x)))}else E=null==k?void 0:k.codecSet,b=null==k?void 0:k.videoRange;for(var N,U,B=f?f.duration:h?h.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,H=[],V=function(){var t=g[K],o=K>d;if(!t)return 0;if(y.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var h=navigator.mediaCapabilities;"function"==typeof(null==h?void 0:h.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,c=u?parseInt(u):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group ".concat(r," not found"));Object.keys(i.channels).forEach(function(t){e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some(function(e){return at(e)})||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!d&&X(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,R,b,A,e,L)?(t.supportedPromise=xt(t,R,h,l.supportedCache),t.supportedPromise.then(function(e){if(l.hls){t.supportedResult=e;var r=l.hls.levels,i=r.indexOf(t);e.error?l.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(i," ").concat(Kt(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&l.log("MediaCapabilities decodingInfo for level ".concat(i," not smooth or powerEfficient: ").concat(Kt(e))):(l.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(i," ").concat(Kt(e))),i>-1&&r.length>1&&(l.log("Removing unsupported level ".concat(i)),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}}).catch(function(e){l.warn("Error handling MediaCapabilities decodingInfo: ".concat(e))})):t.supportedResult=wt}if((E&&t.codecSet!==E||b&&t.videoRange!==b||o&&A>t.frameRate||!o&&A>0&&A<t.frameRate||null!=(N=t.supportedResult)&&null!=(N=N.decodingInfoResults)&&N.some(function(e){return!1===e.smooth}))&&(!S||K!==w))return H.push(K),0;var v,p=t.details,k=(f?null==p?void 0:p.partTarget:null==p?void 0:p.averagetargetduration)||B;v=o?s*e:a*e;var I=B&&i>=2*B&&0===n?t.averageBitrate:t.maxBitrate,P=l.getTimeToLoadFrag(G,v,I*k,void 0===p);if(v>=I&&(K===c||0===t.loadError&&0===t.fragmentError)&&(P<=G||!X(P)||T&&!l.bitrateTestDelay||P<u)){var x=l.forcedAutoLevel;return K===m||-1!==x&&x===m||(H.length&&l.trace("Skipped level(s) ".concat(H.join(",")," of ").concat(r,' max with CODECS and VIDEO-RANGE:"').concat(g[H[0]].codecs,'" ').concat(g[H[0]].videoRange,'; not compatible with "').concat(E,'" ').concat(b)),l.info("switch candidate:".concat(d,"->").concat(K," adjustedbw(").concat(Math.round(v),")-bitrate=").concat(Math.round(v-I)," ttfb:").concat(G.toFixed(1)," avgDuration:").concat(k.toFixed(1)," maxFetchDuration:").concat(u.toFixed(1)," fetchDuration:").concat(P.toFixed(1)," firstSelection:").concat(S," codecSet:").concat(t.codecSet," videoRange:").concat(t.videoRange," hls.loadLevel:").concat(m))),S&&(l.firstSelection=K),{v:K}}},K=r;K>=t;K--)if(0!==(U=V())&&U)return U.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)}}])}(ve),Zt=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function er(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.005,a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===tr(r,i,a)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=Zt(t,tr.bind(null,r,i));return!o||o===e&&a?a:o}function tr(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2?arguments[2]:void 0;if(r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function rr(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function ir(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),Zt(n,function(e){return e.cc<t?1:e.cc>t?-1:(i=e,e.end<=r?1:e.start>r?-1:0)}),i||null}return null}function nr(e){switch(e.details){case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_TIMEOUT:case Z.LEVEL_LOAD_TIMEOUT:case Z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ar(e){return e.details.startsWith("key")}function sr(e){return ar(e)&&!!e.frag&&!e.frag.decryptdata}function or(e,t){var r=nr(t);return e.default["".concat(r?"timeout":"error","Retry")]}function lr(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function ur(e){return fe(fe({},e),{errorRetry:null,timeoutRetry:null})}function cr(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t<e.maxNumRetry&&(function(e){return dr(e)||!!e&&(e<400||e>499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function dr(e){return 0===e&&!1===navigator.onLine}var hr=0,fr=2,vr=3,gr=5,pr=0,mr=1,yr=2,Er=4,kr=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["error-controller",e.logger])).hls=void 0,r.playlistError=0,r.hls=e,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.ERROR,this.onError,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.ERROR,this.onError,this),e.off(ee.ERROR,this.onErrorOut,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.hls=null}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.playlistError=0}},{key:"getVariantLevelIndex",value:function(e){return(null==e?void 0:e.type)===ae?e.level:this.getVariantIndex()}},{key:"getVariantIndex",value:function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}},{key:"variantHasKey",value:function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(function(e){return i.indexOf(e.groupId)>=0}).some(function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)})}return!1}},{key:"onManifestLoading",value:function(){this.playlistError=0}},{key:"onLevelUpdated",value:function(){this.playlistError=0}},{key:"onError",value:function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Z.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=Tr());case Z.FRAG_GAP:case Z.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=fr);case Z.LEVEL_EMPTY_ERROR:case Z.LEVEL_PARSING_ERROR:var a,s=t.parent===ae?t.level:i.loadLevel;return void(t.details===Z.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(a=a.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,s)));case Z.LEVEL_LOAD_ERROR:case Z.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.SUBTITLE_LOAD_ERROR:case Z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===ie&&o.hasAudioGroup(n.groupId)||n.type===ne&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=fr,void(t.errorAction.flags=mr)}return;case Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:fr,flags:yr});case Z.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Z.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:fr,flags:Er});case Z.BUFFER_ADD_CODEC_ERROR:case Z.REMUX_ALLOC_ERROR:case Z.BUFFER_APPEND_ERROR:var l;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(l=t.level)?l:i.loadLevel);return;case Z.INTERNAL_EXCEPTION:case Z.BUFFER_APPENDING_ERROR:case Z.BUFFER_FULL_ERROR:case Z.LEVEL_SWITCH_ERROR:case Z.BUFFER_STALLED_ERROR:case Z.BUFFER_SEEK_OVER_HOLE:case Z.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Tr())}t.type===J.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Tr())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var r=or(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(cr(r,i,nr(e),e.response))return{action:gr,flags:pr,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=or(ar(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(i&&(e.details!==Z.FRAG_GAP&&i.fragmentError++,!sr(e)&&cr(o,l,nr(e),e.response)))return{action:gr,flags:pr,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,s===Z.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,c=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var h,f,v,g=null==(n=e.frag)?void 0:n.type,p=(g===se&&s===Z.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR))&&l.some(function(e){var t=e.audioCodec;return i.audioCodec!==t}),m="video"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR)&&l.some(function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r}),y=null!=(a=e.context)?a:{},E=y.type,k=y.groupId,T=function(){var t=(S+u)%l.length;if(t!==u&&t>=c&&t<=d&&0===l[t].loadError){var r=l[t];if(s===Z.FRAG_GAP&&g===ae&&e.frag){var n=l[t].details;if(n){var a=er(e.frag,n.fragments,e.frag.start);if(null!=a&&a.gap)return 0}}else{if(E===ie&&r.hasAudioGroup(k)||E===ne&&r.hasSubtitleGroup(k))return 0;if(g===se&&null!=(h=i.audioGroups)&&h.some(function(e){return r.hasAudioGroup(e)})||g===oe&&null!=(f=i.subtitleGroups)&&f.some(function(e){return r.hasSubtitleGroup(e)})||p&&i.audioCodec===r.audioCodec||m&&i.codecSet===r.codecSet||!p&&i.codecSet!==r.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(v=T())||1!==v););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:fr,flags:pr,nextAutoLevel:o}}return{action:fr,flags:mr}}},{key:"onErrorOut",value:function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case hr:break;case fr:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Z.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'.concat(t.sourceBufferName,'" sourceBuffer append error. Attempting to recover from media error.')),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}},{key:"sendAlternateToPenaltyBox",value:function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,n=r.nextAutoLevel;switch(i){case pr:this.switchLevel(e,n);break;case yr:var a=this.getVariantLevelIndex(e.frag),s=t.levels[a],o=null==s?void 0:s.attrs["HDCP-LEVEL"];if(r.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=_t[_t.indexOf(o)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'));break}case Er:var l=e.decryptdata;if(l){for(var u=this.hls.levels,c=u.length,d=c;d--;){var h,f;if(this.variantHasKey(u[d],l))this.log("Banned key found in level ".concat(d," (").concat(u[d].bitrate,'bps) or audio group "').concat(null==(h=u[d].audioGroups)?void 0:h.join(","),'" (').concat(null==(f=e.frag)?void 0:f.type," fragment) ").concat(Ae(l.keyId||[]))),u[d].fragmentError++,u[d].loadError++,this.log("Removing level ".concat(d," with key error (").concat(e.error,")")),this.hls.removeLevel(d)}var v=e.frag;if(this.hls.levels.length<c)r.resolved=!0;else if(v&&v.type!==ae){var g=v.decryptdata;g&&!l.matches(g)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(e,n)}}},{key:"switchLevel",value:function(e,t){if(void 0!==t&&e.errorAction&&(this.warn("switching to level ".concat(t," after ").concat(e.details)),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===Z.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=It(e.mimeType),i=this.hls.levels,n=i.length;n--;)i[n]["".concat(e.sourceBufferName,"Codec")]===r&&(this.log("Removing level ".concat(n," for ").concat(e.details,' ("').concat(r,'" not supported)')),this.hls.removeLevel(n))}}])}(ve);function Tr(e){var t={action:hr,flags:pr};return e&&(t.resolved=!0),t}var Sr="NOT_LOADED",br="APPENDING",Ar="PARTIAL",Lr="OK",Ir=function(){return o(function e(t){a(this,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=t,this._registerListeners()},[{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.FRAG_LOADED,this.onFragLoaded,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this))}},{key:"destroy",value:function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}},{key:"getAppendedFrag",value:function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}},{key:"getBufferedFrag",value:function(e,t){return this.getFragAtPos(e,t,!0)}},{key:"getFragAtPos",value:function(e,t,r){for(var i=this.fragments,n=Object.keys(i),a=n.length;a--;){var s=i[n[a]];if((null==s?void 0:s.body.type)===t&&(!r||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,r,i,n){var a=this;this.timeRanges&&(this.timeRanges[e]=t);var s=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(i){var o=a.fragments[i];if(o&&!(s>=o.body.sn))if(o.buffered||o.loaded&&!n){var l=o.range[e];l&&(0!==l.time.length?l.time.some(function(e){var r=!a.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&a.removeFragment(o.body),r}):a.removeFragment(o.body))}else o.body.type===r&&a.removeFragment(o.body)})}},{key:"detectPartialFragments",value:function(e){var t=this,r=this.timeRanges;if(r&&"initSegment"!==e.frag.sn){var i=e.frag,n=wr(i),a=this.fragments[n];if(!(!a||a.buffered&&i.gap)){var s=!i.relurl;if(Object.keys(r).forEach(function(n){var o=i.elementaryStreams[n];if(o){var l=r[n],u=s||!0===o.partial;a.range[n]=t.getBufferedTimes(i,e.part,u,l)}}),a.loaded=null,Object.keys(a.range).length)a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Rr(a)||this.removeParts(i.sn-1,i.type);else this.removeFragment(a.body)}}}},{key:"removeParts",value:function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Pr(r,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var r=wr(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}},{key:"getBufferedTimes",value:function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<i.length;u++){var c=i.start(u)-this.bufferPadding,d=i.end(u)+this.bufferPadding;if(l>=c&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(a<d&&s>c){var h=Math.max(a,i.start(u)),f=Math.min(s,i.end(u));f>h&&(n.partial=!0,n.time.push({startPTS:h,endPTS:f}))}else if(s<=c)break}return n}},{key:"getPartialFragment",value:function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&Rr(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))}),n}},{key:"isEndListAppended",value:function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Rr(t))}},{key:"getState",value:function(e){var t=wr(e),r=this.fragments[t];return r?r.buffered?Rr(r)?Ar:Lr:br:Sr}},{key:"isTimeBuffered",value:function(e,t,r){for(var i,n,a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1}},{key:"onManifestLoading",value:function(){this.removeAllFragments()}},{key:"onFragLoaded",value:function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=wr(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var r=t.frag,i=t.part,n=t.timeRanges,a=t.type;if("initSegment"!==r.sn){var s=r.type;if(i){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(i)}this.timeRanges=n;var l=n[a];this.detectEvictedFragments(a,l,s,i)}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=wr(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1}},{key:"hasParts",value:function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}},{key:"removeFragmentsInRange",value:function(e,t,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=wr(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Pr(r,function(e){return e.fragment.sn!==i})}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}},{key:"removeAllFragments",value:function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(function(e){return e.clearElementaryStreamInfo()})}}])}();function Rr(e){var t,r,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial)}function wr(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function Pr(e,t){return e.filter(function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r})}var xr=0,Dr=1,Cr=function(){return o(function e(t,r,i){a(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=i},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case xr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Dr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode ".concat(this.aesMode))}}}])}();var _r=function(){return o(function e(){a(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()},[{key:"uint8ArrayToUint32Array_",value:function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256),f=0,v=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var p=v^v<<1^v<<2^v<<3^v<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var m=h[f],y=h[m],E=h[y],k=257*h[p]^16843008*p;i[f]=k<<24|k>>>8,n[f]=k<<16|k>>>16,a[f]=k<<8|k>>>24,s[f]=k,k=16843009*E^65537*y^257*m^16843008*f,l[p]=k<<24|k>>>8,u[p]=k<<16|k>>>16,c[p]=k<<8|k>>>24,d[p]=k,f?(f=m^h[h[h[E^m]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var a,s,o,l,u=this.ksRows=4*(n+6+1),c=this.keySchedule=new Uint32Array(u),d=this.invKeySchedule=new Uint32Array(u),h=this.sBox,f=this.rcon,v=this.invSubMix,g=v[0],p=v[1],m=v[2],y=v[3];for(a=0;a<u;a++)a<n?o=c[a]=t[a]:(l=o,a%n===0?(l=h[(l=l<<8|l>>>24)>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l],l^=f[a/n|0]<<24):n>6&&a%n===4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),c[a]=o=(c[a-n]^l)>>>0);for(s=0;s<u;s++)a=u-s,l=3&s?c[a]:c[a-4],d[s]=s<4||a<=4?l:g[h[l>>>24]]^p[h[l>>>16&255]]^m[h[l>>>8&255]]^y[h[255&l]],d[s]=d[s]>>>0}}},{key:"networkToHostOrderSwap",value:function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var i,n,a,s,o,l,u,c,d,h,f,v,g,p,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,k=this.invSubMix,T=k[0],S=k[1],b=k[2],A=k[3],L=this.uint8ArrayToUint32Array_(r),I=L[0],R=L[1],w=L[2],P=L[3],x=new Int32Array(e),D=new Int32Array(x.length),C=this.networkToHostOrderSwap;t<x.length;){for(d=C(x[t]),h=C(x[t+1]),f=C(x[t+2]),v=C(x[t+3]),o=d^y[0],l=v^y[1],u=f^y[2],c=h^y[3],g=4,p=1;p<m;p++)i=T[o>>>24]^S[l>>16&255]^b[u>>8&255]^A[255&c]^y[g],n=T[l>>>24]^S[u>>16&255]^b[c>>8&255]^A[255&o]^y[g+1],a=T[u>>>24]^S[c>>16&255]^b[o>>8&255]^A[255&l]^y[g+2],s=T[c>>>24]^S[o>>16&255]^b[l>>8&255]^A[255&u]^y[g+3],o=i,l=n,u=a,c=s,g+=4;i=E[o>>>24]<<24^E[l>>16&255]<<16^E[u>>8&255]<<8^E[255&c]^y[g],n=E[l>>>24]<<24^E[u>>16&255]<<16^E[c>>8&255]<<8^E[255&o]^y[g+1],a=E[u>>>24]<<24^E[c>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[g+2],s=E[c>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&u]^y[g+3],D[t]=C(i^I),D[t+1]=C(s^R),D[t+2]=C(a^w),D[t+3]=C(n^P),I=d,R=h,w=f,P=v,t+=4}return D.buffer}}])}(),Mr=function(){return o(function e(t,r,i){a(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=r,this.aesMode=i},[{key:"expandKey",value:function(){var e=function(e){switch(e){case xr:return"AES-CBC";case Dr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode ".concat(e))}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}])}();var Or=function(){return o(function e(t){var r=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).removePKCS7Padding,i=void 0===r||r;if(a(this,e),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=t.enableSoftwareAES,this.removePKCS7Padding=i,i)try{var n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle},[{key:"destroy",value:function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{key:"isSync",value:function(){return this.useSoftware}},{key:"flush",value:function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r,i,n,a=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(i=(r=a).byteLength,(n=i&&new DataView(r.buffer).getUint8(i-1))?r.slice(0,i-n):r):a}},{key:"reset",value:function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}},{key:"decrypt",value:function(e,t,r,i){var n=this;return this.useSoftware?new Promise(function(a,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);n.softwareDecrypt(o,t,r,i);var l=n.flush();l?a(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)}},{key:"softwareDecrypt",value:function(e,t,r,i){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(i!==xr||16!==t.byteLength)return ke.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=it(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new _r),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,r,i){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new Mr(this.subtle,t,i)}return this.fastAesKey.expandKey().then(function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new Cr(n.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return ke.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),n.onWebCryptoError(e,t,r,i)})}},{key:"onWebCryptoError",value:function(e,t,r,i){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}},{key:"getValidChunk",value:function(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(ke.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),Fr=Math.pow(2,17),Nr=function(){return o(function e(t){a(this,e),this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t},[{key:"destroy",value:function(){this.loader&&(this.loader.destroy(),this.loader=null)}},{key:"abort",value:function(){this.loader&&this.loader.abort()}},{key:"load",value:function(e,t){var r=this,i=e.url;if(!i)return Promise.reject(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(i?"part list":"url")),networkDetails:null}));this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(r.loader&&r.loader.destroy(),e.gap){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void l(Br(e));e.gap=!1}var u=r.loader=a?new a(n):new s(n),c=Ur(e);e.loader=u;var d=ur(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Fr};e.stats=u.stats;var f={onSuccess:function(t,i,n,a){r.resetLoader(e,u);var s=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),o({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,n,a,s){r.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:fe({url:i,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:a,stats:s}))},onAbort:function(t,i,n){r.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,i,n){r.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:n,stats:t}))}};t&&(f.onProgress=function(r,i,n,a){return t({frag:e,part:null,payload:n,networkDetails:a})}),u.load(c,h,f)})}},{key:"loadPart",value:function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(i.loader&&i.loader.destroy(),e.gap||t.gap)l(Br(e,t));else{var u=i.loader=a?new a(n):new s(n),c=Ur(e,t);e.loader=u;var d=ur(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Fr};t.stats=u.stats,u.load(c,h,{onSuccess:function(n,a,s,l){i.resetLoader(e,u),i.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:n.data,networkDetails:l};r(c),o(c)},onError:function(r,n,a,s){i.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:fe({url:c.url,data:void 0},r),error:new Error("HTTP Error ".concat(r.code," ").concat(r.text)),networkDetails:a,stats:s}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,n,a){i.resetLoader(e,u),l(new Gr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:a,stats:r}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end}},{key:"resetLoader",value:function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}])}();function Ur(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=r||e,n={frag:e,part:r,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},a=i.byteRangeStartOffset,s=i.byteRangeEndOffset;if(X(a)&&X(s)){var o,l=a,u=s;if("initSegment"===e.sn&&("AES-128"===(t=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===t)){var c=s-a;c%16&&(u=s+(16-c%16)),0!==a&&(n.resetIV=!0,l=a-16)}n.rangeStart=l,n.rangeEnd=u}return n}function Br(e,t){var r=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),i={type:J.MEDIA_ERROR,details:Z.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Gr(i)}var Gr=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e.error.message])).data=void 0,r.data=e,r}return d(t,e),o(t)}(L(Error)),Hr=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[e,r]))._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}return d(t,e),o(t,[{key:"destroy",value:function(){this.onHandlerDestroying(),this.onHandlerDestroyed()}},{key:"onHandlerDestroying",value:function(){this.clearNextTick(),this.clearInterval()}},{key:"onHandlerDestroyed",value:function(){}},{key:"hasInterval",value:function(){return!!this._tickInterval}},{key:"hasNextTick",value:function(){return!!this._tickTimer}},{key:"setInterval",value:function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}},{key:"clearInterval",value:function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}},{key:"clearNextTick",value:function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}},{key:"tick",value:function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}},{key:"tickImmediate",value:function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{key:"doTick",value:function(){}}])}(ve),Vr=o(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];a(this,e),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=t,this.sn=r,this.id=i,this.size=n,this.part=s,this.partial=o});var Kr={length:0,start:function(){return 0},end:function(){return 0}},jr=function(){function e(){a(this,e)}return o(e,null,[{key:"isBuffered",value:function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}},{key:"bufferInfo",value:function(t,r,i){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var i=-1,n=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<r?e[a].end>o&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,c=t,d=t,h=0;h<n.length;h++){var f=n[h].start,v=n[h].end;if(-1===i&&t>=f&&t<=v&&(i=h),t+r>=f&&t<v)c=f,u=(d=v)-t;else if(t+r<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:i}}},{key:"getBuffered",value:function(e){try{return e.buffered||Kr}catch(e){return ke.log("failed to get media.buffered",e),Kr}}}])}(),Yr=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wr(e){return Yr.test(e)}function qr(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(Yr,function(t){var i=t.substring(2,t.length-1),n=null==r?void 0:r[i];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(i,'"'))),t):n})}return t}function zr(e,t,r){var i,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'.concat(i,'" does not match any query parameter in URI: "').concat(r,'"'));n=s.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(t.message)))}}else i=t.NAME,n=t.VALUE;i in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(i,'"'))):a[i]=n||""}function Xr(e,t,r){var i=t.IMPORT;if(r&&i in r){var n=e.variableList;n||(e.variableList=n={}),n[i]=r[i]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(i,'"')))}var Qr=/^(\d+)x(\d+)$/,$r=/(.+?)=(".*?"|.*?)(?:,|$)/g,Jr=function(){return o(function e(t,r){a(this,e),"string"==typeof t&&(t=e.parseAttrList(t,r)),de(this,t)},[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(e){return"X-"===e.substring(0,2)})}},{key:"decimalInteger",value:function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null}},{key:"hexadecimalIntegerAsNumber",value:function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"optionalFloat",value:function(e,t){var r=this[e];return r?parseFloat(r):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce(function(e,t){return e[t.toLowerCase()]=!0,e},t)}},{key:"bool",value:function(e){return"YES"===this[e]}},{key:"decimalResolution",value:function(e){var t=Qr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var r,i={};for($r.lastIndex=0;null!==(r=$r.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=qr(t,a);else if(!o&&!s)switch(n){case"CLOSED-CAPTIONS":if("NONE"===a)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":ke.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}i[n]=a}return i}}])}();function Zr(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function ei(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var ti=function(){return o(function e(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(a(this,e),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==r?void 0:r.tagAnchor)||null,this.tagOrder=null!=(i=null==r?void 0:r.tagOrder)?i:n,r){var s=r.attr;for(var o in s)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==s[o]){ke.warn('DATERANGE tag attribute: "'.concat(o,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=o;break}t=de(new Jr({}),s,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var l=(null==r?void 0:r.endDate)||new Date(this.attr["END-DATE"]);X(l.getTime())&&(this._endDate=l)}},[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var 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}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(ke.warn('Expected tagAnchor Fragment with PDT set for DateRange "'.concat(this.id,'": ').concat(e)),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(X(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&X(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)}}])}(),ri=function(){return o(function e(t){a(this,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=t},[{key:"reloaded",value:function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}},{key:"hasKey",value:function(e){return this.encryptedFragments.some(function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}},{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&X(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function ii(e,t){return e.length===t.length&&!e.some(function(e,r){return e!==t[r]})}function ni(e,t){return!e&&!t||!(!e||!t)&&ii(e,t)}function ai(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function si(e){switch(e){case"AES-128":case"AES-256":return xr;case"AES-256-CTR":return Dr;default:throw new Error("invalid full segment method ".concat(e))}}function oi(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function li(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function ui(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ci(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=oi(l)):(t=li(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var di="undefined"!=typeof self?self:void 0,hi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fi="org.w3.clearkey",vi="com.apple.streamingkeydelivery",gi="com.microsoft.playready",pi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function mi(e){switch(e){case vi:return hi.FAIRPLAY;case gi:return hi.PLAYREADY;case pi:return hi.WIDEVINE;case fi:return hi.CLEARKEY}}function yi(e){switch(e){case hi.FAIRPLAY:return vi;case hi.PLAYREADY:return gi;case hi.WIDEVINE:return pi;case hi.CLEARKEY:return fi}}function Ei(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[hi.FAIRPLAY,hi.WIDEVINE,hi.PLAYREADY,hi.CLEARKEY].filter(function(e){return!!t[e]}):[];return!i[hi.WIDEVINE]&&r&&i.push(hi.WIDEVINE),i}var ki,Ti=null!=di&&null!=(ki=di.navigator)&&ki.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Si(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),i=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){var a=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(a){var s=oi(a).subarray(0,16);return ui(s),s}}return null}var bi={},Ai=function(){function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5?arguments[5]:void 0;a(this,e),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=t,this.uri=r,this.keyFormat=i,this.keyFormatVersions=n,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ai(t),null!=o&&o.startsWith("0x")&&(this.keyId=new Uint8Array(Le(o)))}return o(e,[{key:"matches",value:function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ii(e.keyFormatVersions,this.keyFormatVersions)&&ni(e.iv,this.iv)&&ni(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(ai(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case vi:case pi:case gi:case fi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,r){if(!this.encrypted||!this.uri)return null;if(ai(this.method)){var i=this.iv;return i||("number"!=typeof t&&(ke.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),i=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){var n=bi[this.uri];if(n&&!ii(this.keyId,n)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var a,s=ci(this.uri);if(s)switch(this.keyFormat){case pi:if(this.pssh=s,!this.keyId){var o=function(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,i=0;i+32<r;){var n=ct(new DataView(e,i));t.push(n),i+=n.size}return t}(s.buffer);if(o.length){var l,u=o[0];this.keyId=null!=(l=u.kids)&&l.length?u.kids[0]:null}}this.keyId||(this.keyId=Li(r));break;case gi:var c=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ut(c,0,s),this.keyId=Si(s);break;default:var d=s.subarray(0,16);if(16!==d.length){var h=new Uint8Array(16);h.set(d,16-d.length),d=h}this.keyId=d}this.keyId&&16===this.keyId.byteLength||(a=function(e){var t=null==e?void 0:e[pi];if(t)return t.keyId;return null}(r),a||(a=Li(r))||(a=bi[this.uri]),a&&(this.keyId=a,e.setKeyIdForUri(this.uri,a)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){bi={}}},{key:"setKeyIdForUri",value:function(e,t){bi[e]=t}}])}();function Li(e){var t=null==e?void 0:e[gi];if(t){var r=ci(t.uri);if(r)return Si(r)}return null}var Ii=/#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,Ri=/#EXT-X-MEDIA:(.*)/g,wi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),xi=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("|")),Di=function(){function e(){a(this,e)}return o(e,null,[{key:"findGroup",value:function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}}},{key:"resolve",value:function(e,t){return Pe.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return wi.test(e)}},{key:"parseMasterPlaylist",value:function(t,r){var i,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Wr(t)},a=[];if(Ii.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(i=Ii.exec(t));)if(i[1]){var s,o=new Jr(i[1],n),l=qr(n,i[2]),u={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,r)},c=o.decimalResolution("RESOLUTION");c&&(u.width=c.width,u.height=c.height),Fi(o.CODECS,u);var d=o["SUPPLEMENTAL-CODECS"];d&&(u.supplemental={},Fi(d,u.supplemental)),null!=(s=u.unknownCodecs)&&s.length||a.push(u),n.levels.push(u)}else if(i[3]){var h=i[3],f=i[4];switch(h){case"SESSION-DATA":var v=new Jr(f,n),g=v["DATA-ID"];g&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[g]=v);break;case"SESSION-KEY":var p=Mi(f,r,n);p.encrypted&&p.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(p)):ke.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(f,'"'));break;case"DEFINE":zr(n,new Jr(f,n),r);break;case"CONTENT-STEERING":var m=new Jr(f,n);n.contentSteering={uri:e.resolve(m["SERVER-URI"],r),pathwayId:m["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Oi(f)}}var y=a.length>0&&a.length<n.levels.length;return n.levels=y?a:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n}},{key:"parseMasterPlaylistMedia",value:function(t,r,i){var n,a={},s=i.levels,o={AUDIO:s.map(function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}}),SUBTITLES:s.map(function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}}),"CLOSED-CAPTIONS":[]},l=0;for(Ri.lastIndex=0;null!==(n=Ri.exec(t));){var u=new Jr(n[1],i),c=u.TYPE;if(c){var d=o[c],h=a[c]||[];a[c]=h;var f=u.LANGUAGE,v=u["ASSOC-LANGUAGE"],g=u.CHANNELS,p=u.CHARACTERISTICS,m=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?e.resolve(u.URI,r):""};if(v&&(y.assocLang=v),g&&(y.channels=g),p&&(y.characteristics=p),m&&(y.instreamId=m),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Ni(y,E,"audioCodec"),Ni(y,E,"textCodec")}h.push(y)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,r,i,n,a){var s,o,l,u,c,d={url:t},h=new ri(t),f=h.fragments,v=[],g=null,p=0,m=0,y=0,E=0,k=0,T=null,S=new Fe(i,d),b=-1,A=!1,L=null;if(Pi.lastIndex=0,h.m3u8=e,h.hasVariableRefs=Wr(e),"#EXTM3U"!==(null==(s=Pi.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=Pi.exec(e));){A&&(A=!1,(S=new Fe(i,d)).playlistOffset=y,S.setStart(y),S.sn=p,S.cc=E,k&&(S.bitrate=k),S.level=r,g&&(S.initSegment=g,g.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),L&&(S.setByteRange(L),L=null)));var I=o[1];if(I){S.duration=parseFloat(I);var R=(" "+o[2]).slice(1);S.title=R||null,S.tagList.push(R?["INF",I,R]:["INF",I])}else if(o[3]){if(X(S.duration)){S.playlistOffset=y,S.setStart(y),u&&Gi(S,u,h),S.sn=p,S.level=r,S.cc=E,f.push(S);var w=(" "+o[3]).slice(1);S.relurl=qr(h,w),Ui(S,T,v),T=S,y+=S.duration,p++,m=0,A=!0}}else{if(!(o=o[0].match(xi))){ke.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<o.length&&void 0===o[l];l++);var P=(" "+o[l]).slice(1),x=(" "+o[l+1]).slice(1),D=o[l+2]?(" "+o[l+2]).slice(1):null;switch(P){case"BYTERANGE":T?S.setByteRange(x,T):S.setByteRange(x);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=x,S.tagList.push(["PROGRAM-DATE-TIME",x]),-1===b&&(b=f.length);break;case"PLAYLIST-TYPE":h.type&&Hi(h,P,o),h.type=x.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Hi(h,P,o):f.length>0&&Vi(h,P,o),p=h.startSN=parseInt(x);break;case"SKIP":h.skippedSegments&&Hi(h,P,o);var C=new Jr(x,h),_=C.decimalInteger("SKIPPED-SEGMENTS");if(X(_)){h.skippedSegments+=_;for(var M=_;M--;)f.push(null);p+=_}var O=C.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(O.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&Hi(h,P,o),h.targetduration=Math.max(parseInt(x),1);break;case"VERSION":null!==h.version&&Hi(h,P,o),h.version=parseInt(x);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Hi(h,P,o),h.live=!1;break;case"#":(x||D)&&S.tagList.push(D?[x,D]:[x]);break;case"DISCONTINUITY":E++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([P]);break;case"BITRATE":S.tagList.push([P,x]),k=1e3*parseInt(x),X(k)?S.bitrate=k:k=0;break;case"DATERANGE":var F=new Jr(x,h),N=new ti(F,h.dateRanges[F.ID],h.dateRangeTagCount);h.dateRangeTagCount++,N.isValid||h.skippedSegments?h.dateRanges[N.id]=N:ke.warn('Ignoring invalid DATERANGE tag: "'.concat(x,'"')),S.tagList.push(["EXT-X-DATERANGE",x]);break;case"DEFINE":var U=new Jr(x,h);"IMPORT"in U?Xr(h,U,a):zr(h,U,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?Hi(h,P,o):f.length>0&&Vi(h,P,o),h.startCC=E=parseInt(x);break;case"KEY":var B=Mi(x,t,h);if(B.isSupported()){if("NONE"===B.method){u=void 0;break}u||(u={});var G=u[B.keyFormat];null!=G&&G.matches(B)||(G&&(u=de({},u)),u[B.keyFormat]=B)}else ke.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(x,'"'));break;case"START":h.startTimeOffset=Oi(x);break;case"MAP":var H=new Jr(x,h);if(S.duration){var V=new Fe(i,d);Bi(V,H,r,u),g=V,S.initSegment=g,g.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime)}else{var K=S.byteRangeEndOffset;if(K){var j=S.byteRangeStartOffset;L="".concat(K-j,"@").concat(j)}else L=null;Bi(S,H,r,u),g=S,A=!0}g.cc=E;break;case"SERVER-CONTROL":c&&Hi(h,P,o),c=new Jr(x),h.canBlockReload=c.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=c.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&c.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=c.optionalFloat("PART-HOLD-BACK",0),h.holdBack=c.optionalFloat("HOLD-BACK",0);break;case"PART-INF":h.partTarget&&Hi(h,P,o);var Y=new Jr(x);h.partTarget=Y.decimalFloatingPoint("PART-TARGET");break;case"PART":var W=h.partList;W||(W=h.partList=[]);var q=m>0?W[W.length-1]:void 0,z=m++,Q=new Jr(x,h),$=new Ne(Q,S,d,z,q);W.push($),S.duration+=$.duration;break;case"PRELOAD-HINT":var J=new Jr(x,h);h.preloadHint=J;break;case"RENDITION-REPORT":var Z=new Jr(x,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(Z);break;default:ke.warn("line parsed but not handled: ".concat(o))}}}T&&!T.relurl?(f.pop(),y-=T.duration,h.partList&&(h.fragmentHint=T)):h.partList&&(Ui(S,T,v),S.cc=E,h.fragmentHint=S,u&&Gi(S,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var ee=f.length,te=f[0],re=f[ee-1];if((y+=h.skippedSegments*h.targetduration)>0&&ee&&re){h.averagetargetduration=y/ee;var ie=re.sn;h.endSN="initSegment"!==ie?ie:0,h.live||(re.endList=!0),b>0&&(!function(e,t){for(var r=e[t],i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(f,b),te&&v.unshift(te))}return h.fragmentHint&&(y+=h.fragmentHint.duration),h.totalduration=y,v.length&&h.dateRangeTagCount&&te&&Ci(v,h),h.endCC=E,h}}])}();function Ci(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var c=r;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=_i(t,u,e,c,a);if(-1!==h){l.tagAnchor=t.fragments[h].ref;break}}}}function _i(e,t,r,i,n){var a=r[i];if(a){var s,o=a.programDateTime;if(t>=o||0===i)if(t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=r[i].sn-e.startSN;if(l<0)return-1;var u=e.fragments;if(u.length>r.length)for(var c=(r[i+1]||u[u.length-1]).sn-e.startSN;c>l;c--){var d=u[c].programDateTime;if(t>=d&&t<d+1e3*u[c].duration)return c}return l}}return-1}function Mi(e,t,r){var i,n,a=new Jr(e,r),s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&ke.error("Invalid IV: ".concat(a.IV));var d=o?Di.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Ai(s,d,c,h,l,a.KEYID)}function Oi(e){var t=new Jr(e).decimalFloatingPoint("TIME-OFFSET");return X(t)?t:null}function Fi(e,t){var r=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text"].forEach(function(e){var i=r.filter(function(t){return ft(t,e)});i.length&&(t["".concat(e,"Codec")]=i.map(function(e){return e.split("/")[0]}).join(","),r=r.filter(function(e){return-1===i.indexOf(e)}))}),t.unknownCodecs=r}function Ni(e,t,r){var i=t[r];i&&(e[r]=i)}function Ui(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Bi(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Gi(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||i.push(e)}function Hi(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(r[0],")"))}function Vi(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(r[0],")"))}function Ki(e,t){var r=t.startPTS;if(X(r)){var i,n=0;t.sn>e.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}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 ji(e,t,r,i,n,a,s){i-r<=0&&(s.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var o=r,l=i,u=t.startPTS,c=t.endPTS;if(X(u)){var d=Math.abs(u-r);e&&d>e.totalduration?s.warn("media timestamps and playlist times differ by ".concat(d,"s for level ").concat(t.level," ").concat(e.url)):X(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,o=Math.max(r,u),r=Math.min(r,u),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,l=Math.min(i,c),i=Math.max(i,c),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var h=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=o,t.startDTS=n,t.endPTS=i,t.minEndPTS=l,t.endDTS=a;var f,v=t.sn;if(!e||v<e.startSN||v>e.endSN)return 0;var g=v-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)Ki(p[f],p[f-1]);for(f=g;f<p.length-1;f++)Ki(p[f],p[f+1]);return e.fragmentHint&&Ki(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function Yi(e,t,r){if(e!==t){for(var i,n=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){n=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=n;u<=a;u++){var c=l[s+u],d=o[u];if(i&&!d&&c&&(d=t.fragments[u]=c),c&&d){r(c,d,u,o);var h=c.relurl,f=d.relurl;if(h&&en(h,f))return void(t.playlistParsingError=Wi("media sequence mismatch ".concat(d.sn,":"),e,t,c,d));if(c.cc!==d.cc)return void(t.playlistParsingError=Wi("discontinuity sequence mismatch (".concat(c.cc,"!=").concat(d.cc,")"),e,t,c,d))}}}(e,t,function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}X(e.startPTS)&&X(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(i=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)});var l=t.fragments,u=t.fragmentHint?l.concat(t.fragmentHint):l;if(n&&u.forEach(function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(function(e){return!e}),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var c=t.skippedSegments;c--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){var i=t.dateRanges,n=t.recentlyRemovedDateranges,a=de({},e);n&&n.forEach(function(e){delete a[e]});var s=Object.keys(a).length;if(!s)return i;return Object.keys(i).forEach(function(e){var t=a[e],n=new ti(i[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(Kt(i[e].attr),'"'))}),a}(e.dateRanges,t,r));var d=e.fragments.filter(function(e){return e.rawProgramDateTime});if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var h=1;h<u.length;h++)null===u[h].programDateTime&&Ui(u[h],u[h-1],d);Ci(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=Qi(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}!function(e,t,r){if(e&&t)for(var i=0,n=0,a=e.length;n<=a;n++){var s=e[n],o=t[n+i];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):i--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),i?ji(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):qi(e,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var g=t.advancedDateTime;if(t.advanced&&g){var p=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=p),t.driftEndTime=g,t.driftEnd=p}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Wi(e,t,r,i,n){return new Error("".concat(e," ").concat(n.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(r.startSN,"\n").concat(r.m3u8))}function qi(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,a=i>=0,s=0;if(a&&i<n.length)s=n[i].start;else if(a&&t.startSN===e.endSN+1)s=e.fragmentEnd;else if(a&&r)s=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;s=e.fragmentStart}zi(t,s)}function zi(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Xi(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var n=1e3*i[i.length-1].duration;n<r&&(r=n)}}else r/=2;return Math.round(r)}function Qi(e,t,r){if(!e)return null;var i=e.fragments[t-e.startSN];return i||((i=e.fragmentHint)&&i.sn===t?i:t<e.startSN&&r&&r.sn===t?r:null)}function $i(e,t,r){return e?Ji(e.partList,t,r):null}function Ji(e,t,r){if(e)for(var i=e.length;i--;){var n=e[i];if(n.index===r&&n.fragment.sn===t)return n}return null}function Zi(e){e.forEach(function(e,t){var r;null==(r=e.details)||r.fragments.forEach(function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function en(e,t){return!(e===t||!t)&&tn(e)!==tn(t)}function tn(e){return e.replace(/\?[^?]*$/,"")}function rn(e,t){for(var r=0,i=e.length;r<i;r++){var n;if((null==(n=e[r])?void 0:n.cc)===t)return e[r]}return null}function nn(e,t){var r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function an(e,t){for(var r=t.fragments,i=0,n=r.length;i<n;i++)nn(r[i],e);t.fragmentHint&&nn(t.fragmentHint,e),t.alignedSliding=!0}function sn(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var r=Math.min(t.endCC,e.endCC),i=rn(t.fragments,r),n=rn(e.fragments,r);if(i&&n)ke.log("Aligning playlist at start of dicontinuity sequence ".concat(r)),an(i.start-n.start,e)}}function on(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var r=e.fragments,i=t.fragments;if(r.length&&i.length){var n,a,s=Math.min(t.endCC,e.endCC);t.startCC<s&&e.startCC<s&&(n=rn(i,s),a=rn(r,s)),n&&a||(a=rn(r,(n=i[Math.floor(i.length/2)]).cc)||r[Math.floor(r.length/2)]);var o=n.programDateTime,l=a.programDateTime;if(o&&l)an((l-o)/1e3-(a.start-n.start),e)}}}function ln(e,t,r){un(e,t,r),e.addEventListener(t,r)}function un(e,t,r){e.removeEventListener(t,r)}var cn=function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="[".concat(e.start(i).toFixed(3),"-").concat(e.end(i).toFixed(3),"]");return t},dn="STOPPED",hn="IDLE",fn="KEY_LOADING",vn="FRAG_LOADING",gn="FRAG_LOADING_WAITING_RETRY",pn="WAITING_TRACK",mn="PARSING",yn="PARSED",En="ENDED",kn="ERROR",Tn="WAITING_INIT_PTS",Sn="WAITING_LEVEL",bn=function(e){function t(e,r,i,s,o){var l;return a(this,t),(l=n(this,t,[s,e.logger])).hls=void 0,l.fragPrevious=null,l.fragCurrent=null,l.fragmentTracker=void 0,l.transmuxer=null,l._state=dn,l.playlistType=void 0,l.media=null,l.mediaBuffer=null,l.config=void 0,l.bitrateTest=!1,l.lastCurrentTime=0,l.nextLoadPosition=0,l.startPosition=0,l.startTimeOffset=null,l.retryDate=0,l.levels=null,l.fragmentLoader=void 0,l.keyLoader=void 0,l.levelLastLoaded=null,l.startFragRequested=!1,l.decrypter=void 0,l.initPTS=[],l.buffering=!0,l.loadingParts=!1,l.loopSn=void 0,l.onMediaSeeking=function(){var e=l,t=e.config,r=e.fragCurrent,i=e.media,n=e.mediaBuffer,a=e.state,s=i?i.currentTime:0,o=jr.bufferInfo(n||i,s,t.maxBufferHole),u=!o.len;if(l.log("Media seeking to ".concat(X(s)?s.toFixed(3):s,", state: ").concat(a,", ").concat(u?"out of":"in"," buffer")),l.state===En)l.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(u||h<o.start||d>o.end){var f=s>h;(s<d||f)&&(f&&r.loader&&(l.log("Cancelling fragment load for seek (sn: ".concat(r.sn,")")),r.abortRequests(),l.resetLoadingState()),l.fragPrevious=null)}}if(i&&(l.fragmentTracker.removeFragmentsInRange(s,1/0,l.playlistType,!0),s>l.lastCurrentTime&&(l.lastCurrentTime=s),!l.loadingParts)){var v=Math.max(o.end,s),g=l.shouldLoadParts(l.getLevelDetails(),v);g&&(l.log("LL-Part loading ON after seeking to ".concat(s.toFixed(2)," with buffer @").concat(v.toFixed(2))),l.loadingParts=g)}l.hls.hasEnoughToStart||(l.log("Setting ".concat(u?"startPosition":"nextLoadPosition"," to ").concat(s," for seek without enough to start")),l.nextLoadPosition=s,u&&(l.startPosition=s)),u&&l.state===hn&&l.tickImmediate()},l.onMediaEnded=function(){l.log("setting startPosition to 0 because media ended"),l.startPosition=l.lastCurrentTime=0},l.playlistType=o,l.hls=e,l.fragmentLoader=new Nr(e.config),l.keyLoader=i,l.fragmentTracker=r,l.config=e.config,l.decrypter=new Or(e.config),l}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"doTick",value:function(){this.onTickEnd()}},{key:"onTickEnd",value:function(){}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){if(this.state!==dn){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var 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=dn}}},{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"pauseBuffering",value:function(){this.buffering=!1}},{key:"resumeBuffering",value:function(){this.buffering=!0}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"_streamEnded",value:function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=jr.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return jr.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}},{key:"getLevelDetails",value:function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"onMediaAttached",value:function(e,t){var r=this.media=this.mediaBuffer=t.media;ln(r,"seeking",this.onMediaSeeking),ln(r,"ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===dn&&this.startLoad(i.startPosition)}},{key:"onMediaDetaching",value:function(e,t){var r=!!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),un(i,"seeking",this.onMediaSeeking),un(i,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}},{key:"onManifestLoading",value:function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}},{key:"onError",value:function(e,t){}},{key:"onManifestLoaded",value:function(e,t){this.startTimeOffset=t.startTimeOffset}},{key:"onHandlerDestroying",value:function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),E(t,"onHandlerDestroying",this,3)([]),this.hls=this.onMediaSeeking=this.onMediaEnded=null}},{key:"onHandlerDestroyed",value:function(){this.state=dn,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,E(t,"onHandlerDestroyed",this,3)([])}},{key:"loadFragment",value:function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}},{key:"_loadFragForPlayback",value:function(e,t,r){var i=this;this._doFragLoad(e,t,r,function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(i.fragInfo(t,!1,e.part),") was dropped during download.")),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===vn||!i.fragCurrent&&t===mn)&&(i.fragmentTracker.removeFragment(r),i.state=hn):("payload"in e&&(i.log("Loaded ".concat(r.type," sn: ").concat(r.sn," of ").concat(i.playlistLabel()," ").concat(r.level)),i.hls.trigger(ee.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}}).catch(function(t){i.state!==dn&&i.state!==kn&&(i.warn("Frag error: ".concat((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,r=this.fragmentTracker;if(r.getState(e)===br){var i=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===Ar&&r.removeFragment(e))}},{key:"checkLiveUpdate",value:function(e){if(e.updated&&!e.live){var 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)}},{key:"waitForLive",value:function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}},{key:"flushMainBuffer",value:function(e,t){if(e-t){var r={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(ee.BUFFER_FLUSHING,r)}}},{key:"_loadInitSegment",value:function(e,t){var r=this;this._doFragLoad(e,t).then(function(e){var t=null==e?void 0:e.frag;if(!t||r.fragContextChanged(t)||!r.levels)throw new Error("init load aborted");return e}).then(function(e){var t=r.hls,i=e.frag,n=e.payload,a=i.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&ai(a.method)){var s=self.performance.now();return r.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,si(a.method)).catch(function(e){throw t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(function(n){var a=self.performance.now();return t.trigger(ee.FRAG_DECRYPTED,{frag:i,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,r.completeInitSegmentLoad(e)})}return r.completeInitSegmentLoad(e)}).catch(function(t){r.state!==dn&&r.state!==kn&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"completeInitSegmentLoad",value:function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==dn&&(this.state=hn),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()}},{key:"unhandledEncryptionError",value:function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in ".concat(this.fragInfo(t)," (media ").concat(a?"attached mediaKeys: "+a.mediaKeys:"detached",")"));return this.warn(s.message),!a||a.mediaKeys?!1:(this.hls.trigger(ee.ERROR,{type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}},{key:"fragContextChanged",value:function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level}},{key:"fragBufferedComplete",value:function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(r?cn(jr.getBuffered(r)):"(detached)",")")),Oe(e)){var i;if(e.type!==oe){var n=e.elementaryStreams;if(!Object.keys(n).some(function(e){return!!n[e]}))return void(this.state=hn)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(this.log("Resetting level fragment error count of ".concat(a.fragmentError," on frag buffered")),a.fragmentError=0)}this.state=hn}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some(function(e){return!e}),s=new Vr(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(s)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"_doFragLoad",value:function(e,t){var r,i=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3?arguments[3]:void 0;this.fragCurrent=e;var s=t.details;if(!this.levels||!s)throw new Error("frag load aborted, missing level".concat(s?"":" detail","s"));var o=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(o=this.keyLoader.loadClear(e,s.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");else if(this.log("Loading key for ".concat(e.sn," of [").concat(s.startSN,"-").concat(s.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=fn,this.fragCurrent=e,o=this.keyLoader.load(e).then(function(e){if(!i.fragContextChanged(e.frag))return i.hls.trigger(ee.KEY_LOADED,e),i.state===fn&&(i.state=hn),e}),this.hls.trigger(ee.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);var l,u=this.fragPrevious;if(Oe(e)&&(!u||e.sn!==u.sn)){var c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log("LL-Part loading ".concat(c?"ON":"OFF"," loading sn ").concat(null==u?void 0:u.sn,"->").concat(e.sn)),this.loadingParts=c)}if(n=Math.max(e.start,n||0),this.loadingParts&&Oe(e)){var d=s.partList;if(d&&a){n>s.fragmentEnd&&s.fragmentHint&&(e=s.fragmentHint);var h=this.getNextPart(d,e,n);if(h>-1){var f,v=d[h];return e=this.fragCurrent=v.fragment,this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(v.index," (").concat(h,"/").concat(d.length-1,") of ").concat(this.fragInfo(e,!1,v),") cc: ").concat(e.cc," [").concat(s.startSN,"-").concat(s.endSN,"], target: ").concat(parseFloat(n.toFixed(3)))),this.nextLoadPosition=v.start+v.duration,this.state=vn,f=o?o.then(function(r){return!r||i.fragContextChanged(r.frag)?null:i.doFragPartsLoad(e,v,t,a)}).catch(function(e){return i.handleFragLoadError(e)}):this.doFragPartsLoad(e,v,t,a).catch(function(e){return i.handleFragLoadError(e)}),this.hls.trigger(ee.FRAG_LOADING,{frag:e,part:v,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(d,n))return Promise.resolve(null)}}if(Oe(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(n.toFixed(2)," Check buffer at sn: ").concat(e.sn," loaded parts: ").concat(null==(l=s.partList)?void 0:l.filter(function(e){return e.loaded}).map(function(e){return"[".concat(e.start,"-").concat(e.end,"]")}))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1),") cc: ").concat(e.cc," ").concat("["+s.startSN+"-"+s.endSN+"]",", target: ").concat(parseFloat(n.toFixed(3)))),X(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=vn;var g,p=this.config.progressive;return g=p&&o?o.then(function(t){return!t||i.fragContextChanged(t.frag)?null:i.fragmentLoader.load(e,a)}).catch(function(e){return i.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,p?a:void 0),o]).then(function(e){var t=m(e,1)[0];return!p&&a&&a(t),t}).catch(function(e){return i.handleFragLoadError(e)}),this.hls.trigger(ee.FRAG_LOADING,{frag:e,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g}},{key:"doFragPartsLoad",value:function(e,t,r,i){var n=this;return new Promise(function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,c=function(t){n.fragmentLoader.loadPart(e,t,i).then(function(i){l[t.index]=i;var s=i.part;n.hls.trigger(ee.FRAG_LOADED,i);var o=$i(r.details,e.sn,t.index+1)||Ji(u,e.sn,t.index+1);if(!o)return a({frag:e,part:s,partsLoaded:l});c(o)}).catch(s)};c(t)})}},{key:"handleFragLoadError",value:function(e){if("data"in e){var t=e.data;t.frag&&t.details===Z.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===J.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(ee.ERROR,t)}else this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}},{key:"_handleTransmuxerFlush",value:function(e){var t=this.getCurrentContext(e);if(t&&this.state===mn){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(r.end.toFixed(2))),this.loadingParts=o),this.updateLevelTiming(r,i,n,e.partial)}else this.fragCurrent||this.state===dn||this.state===kn||(this.state=hn)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r,i,n=e.partList[0];if(n.fragment.type===oe)return!1;if(t>=n.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0))if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment ".concat(n," of ").concat(this.playlistLabel()," ").concat(i,". The current chunk will not be buffered.")),null;var s=t[i],o=s.details,l=a>-1?$i(o,n,a):null,u=l?l.fragment:Qi(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,r,i,n){if(this.state===mn){var a=e.data1,s=e.data2,o=a;if(s&&(o=it(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(ee.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(jr.isBuffered(t,t.currentTime)){var r=t.currentTime,i=jr.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var r,i=this.getLoadPosition();if(!X(i))return null;var n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,r,i){var n=jr.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return jr.bufferInfo(e,t,s)}}return n}},{key:"getMaxBufferLength",value:function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)}},{key:"reduceMaxBufferLength",value:function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to ".concat(n,"s")),!0)}},{key:"getAppendedFrag",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ae,r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}},{key:"getNextFragment",value:function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=r[0].start,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: ".concat(i,", need: ").concat(l,")")),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;s&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);var c=this.hls.startPosition,d=this.hls.liveSyncPosition,h=o?(-1!==c&&c>=a?c:d)||o.start:e;this.log("Setting startPosition to ".concat(h," to match start frag at live edge. mainStart: ").concat(c," liveSyncPosition: ").concat(d," frag.start: ").concat(null==(u=o)?void 0:u.start)),this.startPosition=this.nextLoadPosition=h}}else e<=a&&(o=r[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var v=this.filterReplacedPrimary(o,t);if(!v&&o){var g=o.sn-t.startSN;v=this.filterReplacedPrimary(r[g+1]||null,t)}return this.mapToInitFragWhenRequired(v)}},{key:"isLoopLoading",value:function(e,t){var r=this.fragmentTracker.getState(e);return(r===Lr||r===Ar&&!!e.gap)&&this.nextLoadPosition>t}},{key:"getNextFragmentLoopLoading",value:function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(i,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(An(this.config)&&(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))return!0;return!1}},{key:"filterReplacedPrimary",value:function(e,t){if(!e)return e;if(An(this.config)&&e.type!==oe){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||0===i.start)return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}}var a=null==r?void 0:r.playerQueue;if(a)for(var s=a.length;s--;){var o=a[s].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}},{key:"mapToInitFragWhenRequired",value:function(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}},{key:"getNextPart",value:function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,i>-1&&r<l.start)break;var u=l.loaded;u?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn("Need buffer at ".concat(r," but next unloaded part starts at ").concat(l.start)),i=s),n=u}return i}},{key:"loadedEndOfParts",value:function(e,t){for(var r,i=e.length;i--;){if(!(r=e[i]).loaded)return!1;if(t>r.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(r.programDateTime)),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!X(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i<e.length;++i){var n=e[i];if(rr(t,r,n))return n}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(i.sn)))}i||(i=ir(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}},{key:"getFragmentAtPosition",value:function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,c=a.maxFragLookUpTolerance,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&u);(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),e<t)?i=er(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:c):i=o[o.length-1];if(i){var f=i.sn-r.startSN,v=this.fragmentTracker.getState(i);if((v===Lr||v===Ar&&i.gap)&&(s=i),s&&i.sn===s.sn&&(!h||d[0].fragment.sn>i.sn||!r.live))if(i.level===s.level){var g=o[f+1];i=i.sn<l&&this.fragmentTracker.getState(g)!==Lr?g:null}}return i}},{key:"alignPlaylists",value:function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,a=!t,s=e.alignedSliding&&X(n);if(a||!s&&!n){!function(e,t){e&&(sn(t,e),t.alignedSliding||on(t,e),t.alignedSliding||t.skippedSegments||qi(e,t,!1))}(r,e);var o=e.fragmentStart;return this.log("Live playlist sliding: ".concat(o.toFixed(2)," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(i)),o}return n}},{key:"waitForCdnTuneIn",value:function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}},{key:"setStartPosition",value:function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;null!==a&&X(a)?(r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to ".concat(r," for start time offset ").concat(a," found in ").concat(n?"multivariant":"media"," playlist")),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge ".concat(r)),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+i}this.nextLoadPosition=r+i}},{key:"getLoadPosition",value:function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}},{key:"handleFragLoadAborted",value:function(e,t){this.transmuxer&&e.type===this.playlistType&&Oe(e)&&e.stats.aborted&&(this.log("Fragment ".concat(e.sn).concat(t?" part "+t.index:""," of ").concat(this.playlistLabel()," ").concat(e.level," was aborted")),this.resetFragmentLoading(e))}},{key:"resetFragmentLoading",value:function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===gn)||(this.state=hn)}},{key:"onFragmentOrKeyLoadError",value:function(e,t){var r;if(t.chunkMeta&&!t.frag){var i=this.getCurrentContext(t.chunkMeta);i&&(t.frag=i.frag)}var n=t.frag;if(n&&n.type===e&&this.levels)if(this.fragContextChanged(n)){var a;this.warn("Frag load error must match current frag to retry ".concat(n.url," > ").concat(null==(a=this.fragCurrent)?void 0:a.url))}else{var s=t.details===Z.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);var o=t.errorAction;if(o){var l=o.action,u=o.flags,c=o.retryCount,d=void 0===c?0:c,h=o.retryConfig,f=!!h,v=f&&l===gr,g=f&&!o.resolved&&u===mr,p=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!v&&g&&Oe(n)&&!n.endList&&p&&!sr(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var m,y=dr(null==(m=t.response)?void 0:m.code),E=lr(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=gn,o.resolved=!0,y)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment ".concat(n.sn," of ").concat(e," ").concat(n.level," errored with ").concat(t.details,", retrying loading ").concat(d+1,"/").concat(h.maxNumRetry," in ").concat(E,"ms"))}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn("".concat(t.details," reached or exceeded max retry (").concat(d,")"));s||l===vr||(o.resolved=!0)}else this.state=l===fr?Sn:kn;this.tickImmediate()}else this.state=kn}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!dr(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=hn)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===mn||this.state===yn){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a&&this.warn("Buffer full error while media.currentTime (".concat(this.getLoadPosition(),") is not buffered, flush ").concat(r," buffer")),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}},{key:"resetFragmentErrors",value:function(e){e===se&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==dn&&(this.state=hn)}},{key:"afterBufferFlushed",value:function(e,t,r){if(e){var i=jr.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===En&&this.resetLoadingState()}}},{key:"resetLoadingState",value:function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==dn&&(this.state=hn)}},{key:"resetStartWhenNotLoaded",value:function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var 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}}},{key:"resetWhenMissingContext",value:function(e){this.log("Loading context changed while buffering sn ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(-1===e.level?"<removed>":e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}},{key:"removeUnbufferedFrags",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}},{key:"updateLevelTiming",value:function(e,t,r,i){var n=this,a=r.details;if(a){var s;if(!Object.keys(e.elementaryStreams).reduce(function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment ".concat(e.sn," ").concat(s," duration reliably (").concat(l,")")),t||!1;var u=i?0:ji(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n);return n.hls.trigger(ee.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1))if(0===r.fragmentError&&this.treatAsGap(e,r),null===(null==(s=this.transmuxer)?void 0:s.error)){var o=new Error("Found no media in fragment ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(e.level," resetting transmuxer to fallback to playlist timing"));if(this.warn(o.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(r.url,'"')}),!this.hls)return;this.resetTransmuxer()}this.state=yn,this.log("Parsed ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t),")")),this.hls.trigger(ee.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")}},{key:"playlistLabel",value:function(){return this.playlistType===ae?"level":"track"}},{key:"fragInfo",value:function(e){var t,r,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(n?"part":"frag",":[").concat((null!=(t=i&&!n?e.startPTS:(n||e).start)?t:NaN).toFixed(3),"-").concat((null!=(r=i&&!n?e.endPTS:(n||e).end)?r:NaN).toFixed(3),"]").concat(n&&"main"===e.type?"INDEPENDENT="+(n.independent?"YES":"NO"):"")}},{key:"treatAsGap",value:function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}},{key:"resetTransmuxer",value:function(){var e;null==(e=this.transmuxer)||e.reset()}},{key:"recoverWorkerError",value:function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log("".concat(t,"->").concat(e)))}}])}(Hr);function An(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var Ln=function(){return o(function e(){a(this,e),this.chunks=[],this.dataLength=0},[{key:"push",value:function(e){this.chunks.push(e),this.dataLength+=e.length}},{key:"flush",value:function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n<e.length;n++){var a=e[n];r.set(a,i),i+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)}},{key:"reset",value:function(){this.chunks.length=0,this.dataLength=0}}])}();var In,Rn={exports:{}};var wn=(In||(In=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,i,a,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,a||e,s),l=r?r+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 s(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__||(r=!1)),o.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,s=new Array(a);n<a;n++)s[n]=i[n].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,n,a,s){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,n),!0;case 5:return c.fn.call(c.context,t,i,n,a),!0;case 6:return c.fn.call(c.context,t,i,n,a,s),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,i);break;case 4:c[u].fn.call(c[u].context,t,i,n);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return a(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,n){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn!==t||n&&!o.once||i&&o.context!==i||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||n&&!o[l].once||i&&o[l].context!==i)&&u.push(o[l]);u.length?this._events[a]=1===u.length?u[0]:u:s(this,a)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Rn)),Rn.exports),Pn=Ie(wn),xn="1.6.14",Dn={};function Cn(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 _n(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 Mn(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}function On(e,t){for(var r=t,i=0;_n(e,t);){i+=10,i+=Mn(e,t+6),Cn(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)}function Fn(e,t){return 255===e[t]&&240==(246&e[t+1])}function Nn(e,t){return 1&e[t+1]?7:9}function Un(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Bn(e,t){return t+1<e.length&&Fn(e,t)}function Gn(e,t){if(Bn(e,t)){var r=Nn(e,t);if(t+r>=e.length)return!1;var i=Un(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||Bn(e,n)}return!1}function Hn(e,t,r,i,n){if(!e.samplerate){var a=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s=1+(n>>6&3),o=t[r+3]>>6&3|(1&n)<<2,l="mp4a.40."+s,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;5!==s&&29!==s||(c-=3);var d=[s<<3|(14&c)>>1,(1&c)<<7|o<<3];return ke.log("manifest codec:".concat(i,", parsed codec:").concat(l,", channels:").concat(o,", rate:").concat(u," (ADTS object type:").concat(s," sampling index:").concat(a,")")),{config:d,samplerate:u,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}var h=new Error("invalid ADTS sampling index:".concat(a));e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!0,error:h,reason:h.message})}(t,r,i,n);if(!a)return;de(e,a)}}function Vn(e){return 9216e4/e}function Kn(e,t,r,i,n){var a,s=i+n*Vn(e.samplerate),o=function(e,t){var r=Nn(e,t);if(t+r<=e.length){var i=Un(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,r+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-r;return(a=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}function jn(e,t){return _n(e,t)&&Mn(e,t+6)+10<=e.length-t}function Yn(e){return function(e,t,r,i){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);var s=(d=e,d&&d.buffer instanceof ArrayBuffer&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),o=(s+e.byteLength)/a,l=(s+t)/a,u=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(u+Math.max(r,0),o));var d;return new i(n,u,c-u)}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,Uint8Array)}function Wn(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=be(Yn(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o=be(Yn(e.data,3+r,a));return s="--\x3e"===i?be(Yn(e.data,4+r+a)):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+r+a)),t.mimeType=i,t.pictureType=n,t.description=o,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function qn(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=be(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=be(e.data.subarray(t),!0);t+=r.length+1;var i=be(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=be(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?Wn(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=be(e.data.subarray(t),!0);t+=r.length+1;var i=be(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=be(e.data.subarray(1));return{key:e.type,info:"",data:n}}}(e)}function zn(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Mn(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function Xn(e){for(var t=0,r=[];_n(e,t);){var i=Mn(e,t+6);e[t+5]>>6&1&&(t+=10);for(var n=(t+=10)+i;t+10<n;){var a=zn(e.subarray(t)),s=qn(a);s&&r.push(s),t+=a.size+10}Cn(e,t)&&(t+=10)}return r}function Qn(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function $n(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function Jn(e){for(var t=Xn(e),r=0;r<t.length;r++){var i=t[r];if(Qn(i))return $n(i)}}var Zn=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 ea(){return{type:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",id:-1,pid:-1,inputTimeScale:arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4,sequenceNumber:-1,samples:[],dropped:0}}var ta=function(){return o(function e(){a(this,e),this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null},[{key:"resetInitSegment",value:function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}},{key:"resetTimeStamp",value:function(e){this.initPTS=e,this.resetContiguity()}},{key:"resetContiguity",value:function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}},{key:"canParse",value:function(e,t){return!1}},{key:"appendFrame",value:function(e,t,r){}},{key:"demux",value:function(e,t){this.cachedData&&(e=it(this.cachedData,e),this.cachedData=null);var r,i=On(e,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?Jn(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&X(o))&&(this.basePTS=ra(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var u=this.appendFrame(a,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=n+=u.length):n=l}else jn(e,n)?(i=On(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY}),r=n+=i.length):n++;if(n===l&&r!==l){var c=e.slice(r);this.cachedData?this.cachedData=it(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:ea(),id3Track:s,textTrack:ea()}}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}},{key:"flush",value:function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:ea(),id3Track:this._id3Track,textTrack:ea()}}},{key:"destroy",value:function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}])}(),ra=function(e,t,r){return X(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},ia=null,na=[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],aa=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],sa=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],oa=[0,1,1,4];function la(e,t,r,i,n){if(!(r+24>t.length)){var a=ua(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function ua(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*na[14*(3===r?3-i:3===i?3:4)+n-1],u=aa[3*(3===r?0:2===r?1:2)+a],c=3===o?1:2,d=sa[r][i],h=oa[i],f=8*d*h,v=Math.floor(d*l/u+s)*h;if(null===ia){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ia=g?parseInt(g[1]):0}return!!ia&&ia<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:v,samplesPerFrame:f}}}function ca(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function da(e,t){return t+1<e.length&&ca(e,t)}function ha(e,t){if(t+1<e.length&&ca(e,t)){var r=ua(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=t+i;return n===e.length||da(e,n)}return!1}var fa=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t)).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){E(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Fn(e,t)&&Un(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){Hn(e,this.observer,t,r,e.manifestCodec);var i=Kn(e,t,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}}],[{key:"probe",value:function(e,t){if(!e)return!1;var r=On(e,0),i=(null==r?void 0:r.length)||0;if(ha(e,i))return!1;for(var n=e.length;i<n;i++)if(Gn(e,i))return t.log("ADTS sync word found !"),!0;return!1}}])}(ta),va=function(e,t){var r=0,i=5;t+=i;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,r=r?r<<o|n[0]:n[0],t+=1,i-=o}return r},ga=function(e){function t(e){var r;return a(this,t),(r=n(this,t)).observer=void 0,r.observer=e,r}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){E(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,r){var i=pa(e,t,r,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0);if(!t)return!1;var r=t.length;return 11===e[r]&&119===e[r+1]&&void 0!==Jn(t)&&va(e,r)<16}}])}(ta);function pa(e,t,r,i,n){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,v=7&t[r+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),p=i+n*(1536/s*9e4),m=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:m,pts:p}),l}var ma=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){E(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return ca(e,t)&&4<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){if(null!==this.basePTS)return la(e,t,r,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Jn(t)&&va(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(ha(e,r))return ke.log("MPEG Audio sync word found !"),!0;return!1}}])}(ta),ya=/\/emsg[-/]ID3/i,Ea=function(){return o(function e(t,r){a(this,e),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=r},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,r,i){var n=this.videoTrack=ea("video",1),a=this.audioTrack=ea("audio",1),s=this.txtTrack=ea("text",1);if(this.id3Track=ea("id3",1),this.timeOffset=0,null!=e&&e.byteLength){var o=Xe(e);if(o.video){var l=o.video,u=l.id,c=l.timescale,d=l.codec,h=l.supplemental;n.id=u,n.timescale=s.timescale=c,n.codec=d,n.supplemental=h}if(o.audio){var f=o.audio,v=f.id,g=f.timescale,p=f.codec;a.id=v,a.timescale=g,a.codec=p}s.id=He.text,n.sampleDuration=0,n.duration=a.duration=i}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=it(this.remainderData,e));var a=function(e){var t={valid:null,remainder:null},r=qe(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,t);return n.samples=nt(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}},{key:"flush",value:function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=nt(e,t),{videoTrack:t,audioTrack:ea(),id3Track:i,textTrack:ea()}}},{key:"extractID3Track",value:function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var n=qe(e.samples,["emsg"]);n&&n.forEach(function(e){var n=function(e){var t=e[0],r="",i="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==Ve(e.subarray(u,u+1));)r+=Ve(e.subarray(u,u+1)),u+=1;for(r+=Ve(e.subarray(u,u+1)),u+=1;"\0"!==Ve(e.subarray(u,u+1));)i+=Ve(e.subarray(u,u+1)),u+=1;i+=Ve(e.subarray(u,u+1)),u+=1,n=je(e,12),a=je(e,16),o=je(e,20),l=je(e,24),u=28}else if(1===t){n=je(e,u+=4);var c=je(e,u+=4),d=je(e,u+=4);for(u+=4,s=Math.pow(2,32)*c+d,Q(s)||(s=Number.MAX_SAFE_INTEGER,ke.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=je(e,u),l=je(e,u+=4),u+=4;"\0"!==Ve(e.subarray(u,u+1));)r+=Ve(e.subarray(u,u+1)),u+=1;for(r+=Ve(e.subarray(u,u+1)),u+=1;"\0"!==Ve(e.subarray(u,u+1));)i+=Ve(e.subarray(u,u+1)),u+=1;i+=Ve(e.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(ya.test(n.schemeIdUri)){var a=ka(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Zn.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=ka(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Zn.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{key:"destroy",value:function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}],[{key:"probe",value:function(e){return function(e){for(var t=e.byteLength,r=0;r<t;){var i=je(e,r);if(i>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)}}])}();function ka(e,t){return X(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Ta=function(){return o(function e(t,r,i){a(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Or(r,{removePKCS7Padding:!1})},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,xr)}},{key:"decryptAacSample",value:function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then(function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}).catch(r)}}},{key:"decryptAacSamples",value:function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var r=new Uint8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)e.set(r.subarray(i,i+16),n);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,n){var a=this,s=lt(n.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then(function(o){n.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,i)}).catch(i)}},{key:"decryptAvcSamples",value:function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}}}])}(),Sa=function(){return o(function e(){a(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,r){var i,n,a=t.byteLength,s=e.naluState||0,o=s,l=[],u=0,c=-1,d=0;for(-1===s&&(c=0,d=this.getNALuType(t,0),s=0,u=1);u<a;)if(i=t[u++],s)if(1!==s)if(i)if(1===i){if(n=u-s-1,c>=0){var h={data:t.subarray(c,n),type:d};l.push(h)}else{var f=this.getLastNalUnit(e.samples);f&&(o&&u<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),n>0&&(f.data=it(f.data,t.subarray(0,n)),f.state=0))}u<a?(c=u,d=this.getNALuType(t,u),s=0):s=-1}else s=0;else s=3;else s=i?0:2;else s=i?0:1;if(c>=0&&s>=0){var v={data:t.subarray(c,a),type:d,state:s};l.push(v)}if(0===l.length){var g=this.getLastNalUnit(e.samples);g&&(g.data=it(g.data,t))}return e.naluState=s,l}}])}(),ba=function(){return o(function e(t){a(this,e),this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0},[{key:"loadWord",value:function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}},{key:"skipBits",value:function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&ke.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)>0&&this.bitsAvailable?r<<t|this.readBits(t):r}},{key:"skipLZ",value:function(){var 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()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}}])}(),Aa=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(function(i){var s,u;switch(i.type){case 1:var c=!1;n=!0;var d,h=i.data;if(l&&h.length>4){var f=a.readSliceType(h);2!==f&&4!==f&&7!==f&&9!==f||(c=!0)}if(c)null!=(d=o)&&d.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.frame=!0,o.key=c;break;case 5:n=!0,null!=(s=o)&&s.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,ot(i.data,1,r.pts,t.samples);break;case 7:var v,g;n=!0,l=!0;var p=i.data,m=a.readSPS(p);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(v=e.pixelRatio)?void 0:v[0])!==m.pixelRatio[0]||(null==(g=e.pixelRatio)?void 0:g[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[p];for(var y=p.subarray(1,4),E="avc1.",k=0;k<3;k++){var T=y[k].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(u=o)&&u.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"getNALuType",value:function(e,t){return 31&e[t]}},{key:"readSliceType",value:function(e){var t=new ba(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,n=0;n<e;n++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i}},{key:"readSPS",value:function(e){var t,r,i,n=new ba(e),a=0,s=0,o=0,l=0,u=n.readUByte.bind(n),c=n.readBits.bind(n),d=n.readUEG.bind(n),h=n.readBoolean.bind(n),f=n.skipBits.bind(n),v=n.skipEG.bind(n),g=n.skipUEG.bind(n),p=this.skipScalingList.bind(this);u();var m=u();if(c(5),f(3),u(),g(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),g(),g(),f(1),h())for(r=3!==y?8:12,i=0;i<r;i++)h()&&p(i<6?16:64,n)}g();var E=d();if(0===E)d();else if(1===E)for(f(1),v(),v(),t=d(),i=0;i<t;i++)v();g(),f(1);var k=d(),T=d(),S=c(1);0===S&&f(1),f(1),h()&&(a=d(),s=d(),o=d(),l=d());var b=[1,1];if(h()&&h())switch(u()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(k+1)-2*a-2*s),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}])}(Sa),La=function(e){function t(){var e;a(this,t);for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];return(e=n(this,t,[].concat(i))).initVPS=null,e}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(function(i){var s,u;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts)),o.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var c;if(n=!0,l)null!=(c=o)&&c.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:n=!0,null!=(s=o)&&s.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 39:n=!0,ot(i.data,2,r.pts,t.samples);break;case 32:n=!0,e.vps||("object"!==S(e.params)&&(e.params={}),e.params=de(e.params,a.readVPS(i.data)),a.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,l=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],i.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var d=a.readSPS(i.data);for(var h in e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],"object"!==S(e.params)&&(e.params={}),d.params)e.params[h]=d.params[h]}a.pushParameterSet(e.sps,i.data,e.vps),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0;break;case 34:if(n=!0,"object"===S(e.params)){if(!e.pps){e.pps=[];var f=a.readPPS(i.data);for(var v in f)e.params[v]=f[v]}a.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(u=o)&&u.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts));break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}},{key:"getNALuType",value:function(e,t){return(126&e[t])>>>1}},{key:"ebsp2rbsp",value:function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)}},{key:"pushAccessUnit",value:function(e,r){E(t,"pushAccessUnit",this,3)([e,r]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new ba(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}},{key:"readSPS",value:function(e){var t=new ba(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),v=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=[],y=[],E=0;E<r;E++)m.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(var k=r;k<8;k++)t.readBits(2);for(var T=0;T<r;T++)m[T]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[T]&&t.readUByte();t.readUEG();var S=t.readUEG();3==S&&t.skipBits(1);var b=t.readUEG(),A=t.readUEG(),L=t.readBoolean(),I=0,R=0,w=0,P=0;L&&(I+=t.readUEG(),R+=t.readUEG(),w+=t.readUEG(),P+=t.readUEG());for(var x=t.readUEG(),D=t.readUEG(),C=t.readUEG(),_=t.readBoolean()?0:r;_<=r;_++)t.skipUEG(),t.skipUEG(),t.skipUEG();if((t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean())&&t.readBoolean())for(var M=0;M<4;M++)for(var O=0;O<(3===M?2:6);O++){if(t.readBoolean()){var F=Math.min(64,1<<4+(M<<1));M>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var U=t.readUEG(),B=0,G=0;G<U;G++){var H=!1;if(0!==G&&(H=t.readBoolean()),H){G===U&&t.readUEG(),t.readBoolean(),t.readUEG();for(var V=0,K=0;K<=B;K++){var j=t.readBoolean(),Y=!1;j||(Y=t.readBoolean()),(j||Y)&&V++}B=V}else{var W=t.readUEG(),q=t.readUEG();B=W+q;for(var z=0;z<W;z++)t.readUEG(),t.readBoolean();for(var X=0;X<q;X++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var Q=t.readUEG(),$=0;$<Q;$++){for(var J=0;J<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,re=!0,ie=1,ne=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean())t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte());if(t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean())if(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean()){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var ce=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():ce=t.readBoolean();var de=ce?1:t.readUEG()+1;if(se)for(var he=0;he<de;he++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ve=b,ge=A;if(L){var pe=1,me=1;1===S?pe=me=2:2==S&&(pe=2),ve=b-pe*R-pe*I,ge=A-me*P-me*w}for(var ye=i?["A","B","C"][i]:"",Ee=s<<24|o<<16|l<<8|u,ke=0,Te=0;Te<32;Te++)ke=(ke|(Ee>>Te&1)<<31-Te)>>>0;var Se=ke.toString(16);1===a&&"2"===Se&&(Se="6");var be=n?"H":"L";return{codecString:"hvc1.".concat(ye).concat(a,".").concat(Se,".").concat(be).concat(p,".B0"),params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:p,bit_depth:x+8,bit_depth_luma_minus8:x,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:Z,chroma_format_idc:S,frame_rate:{fixed:re,fps:ne/ie}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new ba(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}}},{key:"matchSPS",value:function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}])}(Sa),Ia=188,Ra=function(){function e(t,r,i,n){a(this,e),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=t,this.config=r,this.typeSupported=i,this.logger=n,this.videoParser=null}return o(e,[{key:"resetInitSegment",value:function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n||(this.sampleAes=null);var s=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,c=s.pid,d=s.pesData,h=o.pid,f=l.pid,v=o.pesData,g=l.pesData,p=null,m=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=it(this.remainderData,t)).length,this.remainderData=null),E<Ia&&!a)return this.remainderData=t,{audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};var k=Math.max(0,e.syncOffset(t));(E-=(E-k)%Ia)<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,S=k;S<E;S+=Ia)if(71===t[S]){var b=!!(64&t[S+1]),A=wa(t,S),L=void 0;if((48&t[S+3])>>4>1){if((L=S+5+t[S+4])===S+Ia)continue}else L=S+4;switch(A){case c:b&&(d&&(i=_a(d,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,u,i,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(L,S+Ia)),d.size+=S+Ia-L);break;case h:if(b){if(v&&(i=_a(v,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i)}v={data:[],size:0}}v&&(v.data.push(t.subarray(L,S+Ia)),v.size+=S+Ia-L);break;case f:b&&(g&&(i=_a(g,this.logger))&&this.parseID3PES(l,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(L,S+Ia)),g.size+=S+Ia-L);break;case 0:b&&(L+=t[L]+1),y=this._pmtId=Pa(t,L);break;case y:b&&(L+=t[L]+1);var I=xa(t,L,this.typeSupported,n,this.observer,this.logger);(c=I.videoPid)>0&&(s.pid=c,s.segmentCodec=I.segmentVideoCodec),(h=I.audioPid)>0&&(o.pid=h,o.segmentCodec=I.segmentAudioCodec),(f=I.id3Pid)>0&&(l.pid=f),null===p||m||(this.logger.warn("MPEG-TS PMT found at ".concat(S," after unknown PID '").concat(p,"'. Backtracking to sync byte @").concat(k," to parse all TS packets.")),p=null,S=k-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=A}}else T++;T>0&&Da(this.observer,new Error("Found ".concat(T," TS packet/s that do not start with 0x47")),void 0,this.logger),s.pesData=d,o.pesData=v,l.pesData=g;var R={audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};return a&&this.extractRemainingSamples(R),R}},{key:"flush",value:function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}},{key:"extractRemainingSamples",value:function(e){var t,r=e.audioTrack,i=e.videoTrack,n=e.id3Track,a=e.textTrack,s=i.pesData,o=r.pesData,l=n.pesData;if(s&&(t=_a(s,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,a,t,!0),i.pesData=null)):i.pesData=s,o&&(t=_a(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t);break;case"ac3":this.parseAC3PES(r,t)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=_a(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l}},{key:"demuxSampleAes",value:function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new Ta(this.observer,this.config,t);return this.decrypt(i,n)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new Aa:"hevc"===e&&(this.videoParser=new La))}},{key:"decrypt",value:function(e,t){return new Promise(function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,function(){n.samples?t.decryptAvcSamples(n.samples,0,0,function(){r(e)}):r(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,function(){r(e)})})}},{key:"destroy",value:function(){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}},{key:"parseAACPES",value:function(e,t){var r,i,n,a=0,s=this.aacOverFlow,o=t.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(-1===l)o=it(s.sample.unit,o);else{var c=u-l;s.sample.unit.set(o.subarray(0,l),c),e.samples.push(s.sample),a=s.missing}}for(r=a,i=o.length;r<i-1&&!Bn(o,r);r++);if(r!==a){var d,h=r<i-1;if(d=h?"AAC PES did not start with ADTS header,offset:".concat(r):"No ADTS header found in AAC PES",Da(this.observer,new Error(d),h,this.logger),!h)return}if(Hn(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)n=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=Vn(e.samplerate);n=s.sample.pts+f}for(var v,g=0;r<i;){if(r+=(v=Kn(e,o,r,n,g)).length,v.missing){this.aacOverFlow=v;break}for(g++;r<i-1&&!Bn(o,r);r++);}}},{key:"parseMPEGPES",value:function(e,t){var r=t.data,i=r.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<i;)if(da(r,a)){var o=la(e,r,a,s,n);if(!o)break;a+=o.length,n++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{key:"parseAC3PES",value:function(e,t){var r=t.data,i=t.pts;if(void 0!==i)for(var n,a=r.length,s=0,o=0;o<a&&(n=pa(e,r,o,i,s++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")}},{key:"parseID3PES",value:function(e,t){if(void 0!==t.pts){var r=de({},t,{type:this._videoTrack?Zn.emsg:Zn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}}],[{key:"probe",value:function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset ".concat(i)),-1!==i}},{key:"syncOffset",value:function(e){for(var t=e.length,r=Math.min(940,t-Ia)+1,i=0;i<r;){for(var n=!1,a=-1,s=0,o=i;o<t;o+=Ia){if(71!==e[o]||t-o!==Ia&&71!==e[o+Ia]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+18612,e.length-Ia)+1),n||(n=0===wa(e,o)),n&&s>1&&(0===a&&s>2||o+Ia>r))return a}i++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:He[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}}])}();function wa(e,t){return((31&e[t+1])<<8)+e[t+2]}function Pa(e,t){return(31&e[t+10])<<8|e[t+11]}function xa(e,t,r,i,n,a){var s={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;){var l=wa(e,t),u=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Ca("ADTS AAC",a);break}case 15:-1===s.audioPid&&(s.audioPid=l);break;case 21:-1===s.id3Pid&&(s.id3Pid=l);break;case 219:if(!i){Ca("H.264",a);break}case 27:-1===s.videoPid&&(s.videoPid=l);break;case 3:case 4:r.mpeg||r.mp3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Ca("AC-3",a);break}case 129:r.ac3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===s.audioPid&&u>0)for(var c=t+5,d=u;d>2;){if(106===e[c])!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=l,s.segmentAudioCodec="ac3");var h=e[c+1]+2;c+=h,d-=h}break;case 194:case 135:return Da(n,new Error("Unsupported EC-3 in M2TS found"),void 0,a),s;case 36:-1===s.videoPid&&(s.videoPid=l,s.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=u+5}return s}function Da(e,t,r,i){i.warn("parsing error: ".concat(t.message)),e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Ca(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function _a(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=it(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn("".concat(Math.round((a-s)/9e4),"s delta between PTS and DTS, align them")),a=s):s=a);var c=(n=r[8])+9;if(e.size<=c)return null;e.size-=c;for(var d=new Uint8Array(e.size),h=0,f=l.length;h<f;h++){var v=(r=l[h]).byteLength;if(c){if(c>v){c-=v;continue}r=r.subarray(c),v-=c,c=0}d.set(r,o),o+=v}return i&&(i-=n+3),{data:d,pts:a,dts:s,len:i}}return null}var Ma=function(){return o(function e(){a(this,e)},null,[{key:"getSilentFrame",value:function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}])}(),Oa=Math.pow(2,32)-1,Fa=function(){function e(){a(this,e)}return o(e,null,[{key:"init",value:function(){var t;for(t in e.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:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=a,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var s=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,s,l,s,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))}},{key:"box",value:function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var a=i.length,s=a;a--;)t+=i[a].byteLength;var o=new Uint8Array(t);for(o[0]=t>>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),a=0,t=8;a<s;a++)o.set(i[a],t),t+=i[a].byteLength;return o}},{key:"hdlr",value:function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var i=Math.floor(r/(Oa+1)),n=Math.floor(r%(Oa+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(Oa+1)),n=Math.floor(r%(Oa+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)}},{key:"sdtp",value:function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r<n.length;r++)i=n[r].flags,a[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return e.box(e.types.sdtp,a)}},{key:"stbl",value:function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}},{key:"avc1",value:function(t){var r,i,n,a=[],s=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,c=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}},{key:"esds",value:function(e){var 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].concat(k(t),[6,1,2]))}},{key:"audioStsd",value:function(e){var 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])}},{key:"mp4a",value:function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))}},{key:"mp3",value:function(t){return e.box(e.types[".mp3"],e.audioStsd(t))}},{key:"ac3",value:function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))}},{key:"stsd",value:function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===r&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===r&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(r,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(Oa+1)),o=Math.floor(i%(Oa+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(Oa+1)),s=Math.floor(r%(Oa+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,n,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(r+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<c;i++)a=(n=u[i]).duration,s=n.size,o=n.flags,l=n.cts,h.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,h)}},{key:"initSegment",value:function(t){e.types||e.init();var r=e.moov(t);return it(e.FTYP,r)}},{key:"hvc1",value:function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s<i.length;s+=1){a+=3;for(var o=0;o<i[s].length;o+=1)a+=2+i[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=i.length-1,c=0;c<i.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,i[c].length]),a),a+=3;for(var d=0;d<i[c].length;d+=1)l.set(new Uint8Array([i[c][d].length>>8,255&i[c][d].length]),a),a+=2,l.set(i[c][d],a),a+=i[c][d].length}var h=e.box(e.types.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],p=t.pixelRatio[1];return e.box(e.types.hvc1,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,f>>8&255,255&f,v>>8&255,255&v,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]),h,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,255&g,p>>24,p>>16&255,p>>8&255,255&p])))}}])}();Fa.types=void 0,Fa.HDLR_TYPES=void 0,Fa.STTS=void 0,Fa.STSC=void 0,Fa.STCO=void 0,Fa.STSZ=void 0,Fa.VMHD=void 0,Fa.SMHD=void 0,Fa.STSD=void 0,Fa.FTYP=void 0,Fa.DINF=void 0;function Na(e,t){var r=e*t*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(r):r}function Ua(e){return Na(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function Ba(e){var t=e.baseTime,r=e.timescale,i=e.trackId;return"".concat(t/r," (").concat(t,"/").concat(r,") trackId: ").concat(i)}var Ga=null,Ha=null;function Va(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ka=function(e){function t(e,r,i,s){var o;if(a(this,t),(o=n(this,t,["mp4-remuxer",s])).observer=void 0,o.config=void 0,o.typeSupported=void 0,o.ISGenerated=!1,o._initPTS=null,o._initDTS=null,o.nextVideoTs=null,o.nextAudioTs=null,o.videoSampleDuration=null,o.isAudioContiguous=!1,o.isVideoContiguous=!1,o.videoTrackConfig=void 0,o.observer=e,o.config=r,o.typeSupported=i,o.ISGenerated=!1,null===Ga){var l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ga=l?parseInt(l[1]):0}if(null===Ha){var u=navigator.userAgent.match(/Safari\/(\d+)/i);Ha=u?parseInt(u[1]):0}return o}return d(t,e),o(t,[{key:"destroy",value:function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}},{key:"resetTimeStamp",value:function(e){var t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log("Reset initPTS: ".concat(t?Ba(t):t," > ").concat(e?Ba(e):e)),this._initPTS=this._initDTS=e}},{key:"resetNextTimestamp",value:function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}},{key:"resetInitSegment",value:function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}},{key:"getVideoStartPts",value:function(e){var t=!1,r=e[0].pts,i=e.reduce(function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=ja(n,r))-e),a>0?e:n},r);return t&&this.debug("PTS rollover detected"),i}},{key:"remux",value:function(e,t,r,i,n,a,s,o){var l,u,c,d,h,f,v=n,g=n,p=e.pid>-1,m=t.pid>-1,y=t.samples.length,E=e.samples.length>0,k=s&&y>0||y>1;if((!p||E)&&(!m||k)||this.ISGenerated||s){if(this.ISGenerated){var T,S,b,A,L=this.videoTrackConfig;(L&&(t.width!==L.width||t.height!==L.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(S=L.pixelRatio)?void 0:S[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(A=L.pixelRatio)?void 0:A[1]))||!L&&k||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));var I,R=this.isVideoContiguous,w=-1;if(k&&(w=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.warn("Dropped ".concat(w," out of ").concat(y," video samples due to a missing keyframe"));var P=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,I=g+=(t.samples[0].pts-P)/t.inputTimeScale}else-1===w&&(this.warn("No keyframe found out of ".concat(y," video samples")),f=!1);if(this.ISGenerated){if(E&&k){var x=this.getVideoStartPts(t.samples),D=(ja(e.samples[0].pts,x)-x)/t.inputTimeScale;v+=Math.max(0,D),g+=Math.max(0,-D)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,v,this.isAudioContiguous,a,m||k||o===se?g:void 0),k){var C=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,g,R,C)}}else k&&(l=this.remuxVideo(t,g,R,0));l&&(l.firstKeyFrame=w,l.independent=-1!==w,l.firstKeyFramePTS=I)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=Ya(r,n,this._initPTS,this._initDTS)),i.samples.length&&(d=Wa(i,n,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}},{key:"computeInitPts",value:function(e,t,r,i){var n=Math.round(r*t),a=ja(e,n);if(a<n+t)for(this.log("Adjusting PTS for rollover in timeline near ".concat((n-a)/t," ").concat(i));a<n+t;)a+=8589934592;return a-n}},{key:"generateIS",value:function(e,t,r,i){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||i,f="audio/mp4",v=-1;if(h&&(n=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}c.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):Fa.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(v=e.id,s=e.inputTimeScale,d&&s===d.timescale?h=!1:n=a=this.computeInitPts(o[0].pts,s,r,"audio"))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Fa.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(v=t.id,s=t.inputTimeScale,d&&s===d.timescale)h=!1;else{var g=this.getVideoStartPts(l),p=ja(l[0].dts,g),m=this.computeInitPts(p,s,r,"video"),y=this.computeInitPts(g,s,r,"video");a=Math.min(a,m),n=Math.min(n,y)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(d&&this.warn("Timestamps at playlist time: ".concat(i?"":"~").concat(r," ").concat(n/s," != initPTS: ").concat(d.baseTime/d.timescale," (").concat(d.baseTime,"/").concat(d.timescale,") trackId: ").concat(d.trackId)),this.log("Found initPTS at playlist time: ".concat(r," offset: ").concat(n/s," (").concat(n,"/").concat(s,") trackId: ").concat(v)),this._initPTS={baseTime:n,timescale:s,trackId:v},this._initDTS={baseTime:a,timescale:s,trackId:v}):n=s=void 0,{tracks:c,initPTS:n,timescale:s,trackId:v}}},{key:"remuxVideo",value:function(e,t,r,i){var n,a,s=e.inputTimeScale,o=e.samples,l=[],u=o.length,c=this._initPTS,d=c.baseTime*s/c.timescale,h=this.nextVideoTs,f=8,v=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===h){var y=d+t*s,E=o[0].pts-ja(o[0].dts,o[0].pts);Ga&&null!==h&&Math.abs(y-E-(h+d))<15e3?r=!0:h=y-E-d}for(var k=h+d,T=0;T<u;T++){var S=o[T];S.pts=ja(S.pts,k),S.dts=ja(S.dts,k),S.dts<o[T>0?T-1:T].dts&&(m=!0)}m&&o.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i}),n=o[0].dts;var b=(a=o[o.length-1].dts)-n,A=b?Math.round(b/(u-1)):v||e.inputTimeScale/30;if(r){var L=n-k,I=L>A,R=L<-1;if((I||R)&&(I?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ua(L,!0)," ms (").concat(L,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ua(-L,!0)," ms (").concat(L,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!R||k>=o[0].pts||Ga)){n=k;var w=o[0].pts-L;if(I)o[0].dts=n,o[0].pts=w;else for(var P=!0,x=0;x<o.length&&!(o[x].dts>w&&P);x++){var D=o[x].pts;if(o[x].dts-=L,o[x].pts-=L,x<o.length-1){var C=o[x+1].pts;P=C<=o[x].pts==C<=D}}this.log("Video: Initial PTS/DTS adjusted: ".concat(Ua(w,!0),"/").concat(Ua(n,!0),", delta: ").concat(Ua(L,!0)," ms"))}}for(var _=0,M=0,O=n=Math.max(0,n),F=0;F<u;F++){for(var N=o[F],U=N.units,B=U.length,G=0,H=0;H<B;H++)G+=U[H].data.length;M+=G,_+=B,N.length=G,N.dts<O?(N.dts=O,O+=A/4|0||1):O=N.dts,g=Math.min(N.pts,g),p=Math.max(N.pts,p)}a=o[u-1].dts;var V,K=M+4*_+8;try{V=new Uint8Array(K)}catch(e){return void this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MUX_ERROR,details:Z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:K,reason:"fail allocating video mdat ".concat(K)})}var j=new DataView(V.buffer);j.setUint32(0,K),V.set(Fa.types.mdat,4);for(var Y=!1,W=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<u;Q++){for(var $=o[Q],te=$.units,re=0,ie=0,ne=te.length;ie<ne;ie++){var ae=te[ie],se=ae.data,oe=ae.data.byteLength;j.setUint32(f,oe),f+=4,V.set(se,f),f+=oe,re+=4+oe}var le=void 0;if(Q<u-1)v=o[Q+1].dts-$.dts,le=o[Q+1].pts-$.pts;else{var ue=this.config,ce=Q>0?$.dts-o[Q-1].dts:A;if(le=Q>0?$.pts-o[Q-1].pts:A,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var he=Math.floor(ue.maxBufferHole*s),fe=(i?g+i*s:this.nextAudioTs+d)-$.pts;fe>he?((v=fe-ce)<0?v=ce:Y=!0,this.log("It is approximately ".concat(fe/90," ms to the next segment; using duration ").concat(v/90," ms for the last video frame."))):v=ce}else v=ce}var ve=Math.round($.pts-$.dts);W=Math.min(W,v),z=Math.max(z,v),q=Math.min(q,le),X=Math.max(X,le),l.push(Va($.key,v,re,ve))}if(l.length)if(Ga){if(Ga<70){var ge=l[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(Ha&&X-q<z-W&&A/z<.025&&0===l[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var pe=n,me=0,ye=l.length;me<ye;me++){var Ee=pe+l[me].duration,ke=pe+l[me].cts;if(me<ye-1){var Te=Ee+l[me+1].cts;l[me].duration=Te-ke}else l[me].duration=me?l[me-1].duration:A;l[me].cts=0,pe=Ee}}var Se=a+(v=Y||!v?A:v);this.nextVideoTs=h=Se-d,this.videoSampleDuration=v,this.isVideoContiguous=!0;var be={data1:Fa.moof(e.sequenceNumber++,n,de(e,{samples:l})),data2:V,startPTS:(g-d)/s,endPTS:(p+v-d)/s,startDTS:(n-d)/s,endDTS:h/s,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,be}},{key:"getSamplesPerFrame",value:function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}},{key:"remuxAudio",value:function(e,t,r,i,n){var a=e.inputTimeScale,s=a/(e.samplerate?e.samplerate:a),o=this.getSamplesPerFrame(e),l=o*s,u=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==n,f=e.samples,v=c?0:8,g=this.nextAudioTs||-1,p=u.baseTime*a/u.timescale,m=p+t*a;if(this.isAudioContiguous=r=r||f.length&&g>0&&(i&&Math.abs(m-(g+p))<9e3||Math.abs(ja(f[0].pts,m)-(g+p))<20*l),f.forEach(function(e){e.pts=ja(e.pts,m)}),!r||g<0){var y=f.length;if(f=f.filter(function(e){return e.pts>=0}),y!==f.length&&this.warn("Removed ".concat(f.length-y," of ").concat(y," samples (initPTS ").concat(p," / ").concat(a,")")),!f.length)return;g=0===n?0:i&&!h?Math.max(0,m-p):f[0].pts-p}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,k=0,T=g+p;k<f.length;k++){var S=f[k],b=S.pts,A=b-T,L=Math.abs(1e3*A/a);if(A<=-E*l&&h)0===k&&(this.warn("Audio frame @ ".concat((b/a).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*A/a)," ms.")),this.nextAudioTs=g=b-p,T=b);else if(A>=E*l&&L<1e4&&h){var I=Math.round(A/l);for(T=b-I*l;T<0&&I&&l;)I--,T+=l;0===k&&(this.nextAudioTs=g=T-p),this.warn("Injecting ".concat(I," audio frames @ ").concat(((T-p)/a).toFixed(3),"s due to ").concat(Math.round(1e3*A/a)," ms gap."));for(var R=0;R<I;R++){var w=Ma.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);w||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),w=S.unit.subarray()),f.splice(k,0,{unit:w,pts:T}),T+=l,k++}}S.pts=T,T+=l}for(var P,x=null,D=null,C=0,_=f.length;_--;)C+=f[_].unit.byteLength;for(var M=0,O=f.length;M<O;M++){var F=f[M],N=F.unit,U=F.pts;if(null!==D){d[M-1].duration=Math.round((U-D)/s)}else{if(r&&"aac"===e.segmentCodec&&(U=g+p),x=U,!(C>0))return;C+=v;try{P=new Uint8Array(C)}catch(e){return void this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MUX_ERROR,details:Z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:C,reason:"fail allocating audio mdat ".concat(C)})}c||(new DataView(P.buffer).setUint32(0,C),P.set(Fa.types.mdat,4))}P.set(N,v);var B=N.byteLength;v+=B,d.push(Va(!0,o,B,0)),D=U}var G=d.length;if(G){var H=d[d.length-1];g=D-p,this.nextAudioTs=g+s*H.duration;var V=c?new Uint8Array(0):Fa.moof(e.sequenceNumber++,x/s,de({},e,{samples:d}));e.samples=[];var K=(x-p)/a,j=g/a,Y={data1:V,data2:P,startPTS:K,endPTS:j,startDTS:K,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:G};return this.isAudioContiguous=!0,Y}}}])}(ve);function ja(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function Ya(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;s<n;s++){var o=e.samples[s];o.pts=ja(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=ja(o.dts-i.baseTime*a/i.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function Wa(e,t,r){var i=e.samples.length;if(i){for(var n=e.inputTimeScale,a=0;a<i;a++){var s=e.samples[a];s.pts=ja(s.pts-r.baseTime*n/r.timescale,t*n)/n}e.samples.sort(function(e,t){return e.pts-t.pts});var o=e.samples;return e.samples=[],{samples:o}}}var qa,za=function(e){function t(e,r,i,s){var o;return a(this,t),(o=n(this,t,["passthrough-remuxer",s])).emitInitSegment=!1,o.audioCodec=void 0,o.videoCodec=void 0,o.initData=void 0,o.initPTS=null,o.initTracks=void 0,o.lastEndTime=null,o.isVideoContiguous=!1,o}return d(t,e),o(t,[{key:"destroy",value:function(){}},{key:"resetTimeStamp",value:function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}},{key:"resetNextTimestamp",value:function(){this.isVideoContiguous=!1,this.lastEndTime=null}},{key:"resetInitSegment",value:function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,i),this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t){var r=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var n=this.initData=Xe(e),a=n.audio,s=n.video;if(t)!function(e,t){if(e&&t){var r=t.keyId;r&&t.isCommonEncryption&&tt(e,function(e,t){var i=e.subarray(8,24);i.some(function(e){return 0!==e})||(ke.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(Ae(i)," -> ").concat(Ae(r))),e.set(r,8))})}}(e,t);else{var o=a||s;null!=o&&o.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(o.codec,'")!'))}a&&(r=Qa(a,De,this)),s&&(i=Qa(s,Ce,this));var l={};a&&s?l.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:r,encrypted:a.encrypted,initSegment:e,id:"audio"}:s?l.video={container:"video/mp4",codec:i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}},{key:"remux",value:function(e,t,r,i,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,c={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};X(u)||(u=this.lastEndTime=n||0);var d=t.samples;if(!d.length)return c;var h={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if(null!=(s=f)&&s.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);var v=function(e,t,r){for(var i={},n=qe(e,["moof","traf"]),a=0;a<n.length;a++){var s=n[a],o=qe(s,["tfhd"])[0],l=je(o,4),u=t[l];if(u){i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:u.timescale,type:u.type});var c=i[l],d=qe(s,["tfdt"])[0];if(d){var h=d[0],f=je(d,4);1===h&&(f===Be?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=Be+1,f+=je(d,8))),X(f)&&(!X(c.start)||f<c.start)&&(c.start=f)}var v=u.default,g=je(o,0)|(null==v?void 0:v.flags),p=(null==v?void 0:v.duration)||0;8&g&&(p=je(o,2&g?12:8));for(var m=qe(s,["trun"]),y=c.start||0,E=0,k=p,T=0;T<m.length;T++){var S=m[T],b=je(S,4),A=c.sampleCount;c.sampleCount+=b;var L=1&S[3],I=4&S[3],R=1&S[2],w=2&S[2],P=4&S[2],x=8&S[2],D=8,C=b;for(L&&(D+=4),I&&b&&(1&S[D+1]||void 0!==c.keyFrameIndex||(c.keyFrameIndex=A),D+=4,R?(k=je(S,D),D+=4):k=p,w&&(D+=4),x&&(D+=4),y+=k,E+=k,C--);C--;)R?(k=je(S,D),D+=4):k=p,w&&(D+=4),P&&(1&S[D+1]||void 0===c.keyFrameIndex&&(c.keyFrameIndex=c.sampleCount-(C+1),c.keyFrameStart=y),D+=4),x&&(D+=4),y+=k,E+=k;!E&&p&&(E+=p*b)}c.duration+=E}}if(!Object.keys(i).some(function(e){return i[e].duration})){for(var _=1/0,M=0,O=qe(e,["sidx"]),F=0;F<O.length;F++){var N=ze(O[F]);if(null!=N&&N.references){_=Math.min(_,N.earliestPresentationTime/N.timescale);var U=N.references.reduce(function(e,t){return e+t.info.duration||0},0);M=Math.max(M,U+N.earliestPresentationTime/N.timescale)}}M&&X(M)&&Object.keys(i).forEach(function(e){i[e].duration||(i[e].duration=M*i[e].timescale-i[e].start)})}return i}(d,f,this),g=f.audio?v[f.audio.id]:null,p=f.video?v[f.video.id]:null,m=Xa(p,1/0),y=Xa(g,1/0),E=Xa(p,0,!0),k=Xa(g,0,!0),T=n,S=0,b=g&&(!p||!l&&y<m||l&&l.trackId===f.audio.id),A=b?g:p;if(A){var L=A.timescale,I=A.start-n*L,R=b?f.audio.id:f.video.id;T=A.start/L,S=b?k-y:E-m,!a&&l||!function(e,t,r,i){if(null===e)return!0;var n=Math.max(i,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>n}(l,T,n,S)&&L===l.timescale||(l&&this.warn("Timestamps at playlist time: ".concat(a?"":"~").concat(n," ").concat(I/L," != initPTS: ").concat(l.baseTime/l.timescale," (").concat(l.baseTime,"/").concat(l.timescale,") trackId: ").concat(l.trackId)),this.log("Found initPTS at playlist time: ".concat(n," offset: ").concat(T-n," (").concat(I,"/").concat(L,") trackId: ").concat(R)),l=null,h.initPTS=I,h.timescale=L,h.trackId=R)}else this.warn("No audio or video samples found for initPTS at playlist time: ".concat(n));l?(h.initPTS=l.baseTime,h.timescale=l.timescale,h.trackId=l.trackId):(h.timescale&&void 0!==h.trackId&&void 0!==h.initPTS||(this.warn("Could not set initPTS"),h.initPTS=T,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});var w=T-l.baseTime/l.timescale,P=w+S;S>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var x=!!f.audio,D=!!f.video,C="";x&&(C+="audio"),D&&(C+="video");var _={data1:d,startPTS:w,startDTS:w,endPTS:P,endDTS:P,type:C,hasAudio:x,hasVideo:D,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=x&&!D?_:void 0,c.video=D?_:void 0;var M=null==p?void 0:p.sampleCount;if(M){var O=p.keyFrameIndex,F=-1!==O;_.nb=M,_.dropped=0===O||this.isVideoContiguous?0:F?O:M,_.independent=F,_.firstKeyFrame=O,F&&p.keyFrameStart&&(_.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=F),this.isVideoContiguous||(this.isVideoContiguous=F),_.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(O,"/").concat(M," dropped: ").concat(_.dropped," start: ").concat(_.firstKeyFramePTS||"NA"))}return c.initSegment=h,c.id3=Ya(r,n,l,l),i.samples.length&&(c.text=Wa(i,n,l)),c}}])}(ve);function Xa(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Qa(e,t,r){var i=e.codec;if(i&&i.length>4)return i;if(t===De){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Tt(i,!1)}return r.warn('Unhandled audio codec "'.concat(i,'" in mp4 MAP')),i||"mp4a"}return r.warn('Unhandled video codec "'.concat(i,'" in mp4 MAP')),i||"avc1"}try{qa=self.performance.now.bind(self.performance)}catch(e){qa=Date.now}var $a=[{demux:Ea,remux:za},{demux:Ra,remux:Ka},{demux:fa,remux:Ka},{demux:ma,remux:Ka}];$a.splice(2,0,{demux:ga,remux:Ka});var Ja=function(){return o(function e(t,r,i,n,s,o){a(this,e),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=t,this.typeSupported=r,this.config=i,this.id=s,this.logger=o},[{key:"configure",value:function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}},{key:"push",value:function(e,t,r,i){var n=this,a=r.transmuxing;a.executeStart=qa();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,p=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,E=l.duration,k=l.initSegmentData,T=function(e,t){var r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(s,t);if(T&&ai(T.method)){var S=this.getDecrypter(),b=si(T.method);if(!S.isSync())return this.asyncResult=!0,this.decryptionPromise=S.webCryptoDecrypt(s,T.key.buffer,T.iv.buffer,b).then(function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t}),this.decryptionPromise;var A=S.softwareDecrypt(s,T.key.buffer,T.iv.buffer,b);if(r.part>-1){var L=S.flush();A=L?L.buffer:L}if(!A)return a.executeEnd=qa(),Za(r);s=new Uint8Array(A)}var I=this.needsProbing(d,h);if(I){var R=this.configureTransmuxer(s);if(R)return this.logger.warn("[transmuxer] ".concat(R.message)),this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),a.executeEnd=qa(),Za(r)}(d||h||g||I)&&this.resetInitSegment(k,p,m,E,t),(d||g||I)&&this.resetInitialTimestamp(y),c||this.resetContiguity();var w=this.transmux(s,T,v,f,r);this.asyncResult=es(w);var P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,a.executeEnd=qa(),w}},{key:"flush",value:function(e){var t=this,r=e.transmuxing;r.executeStart=qa();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then(function(){return t.flush(e)});var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){r.executeEnd=qa();var d=[Za(e)];return this.asyncResult?Promise.resolve(d):d}var h=u.flush(o);return es(h)?(this.asyncResult=!0,h.then(function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,r){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(r.sn).concat(r.part>-1?" part: "+r.part:""," of ").concat(this.id===ae?"level":"track"," ").concat(r.level));var c=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=qa()}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}},{key:"resetContiguity",value:function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}},{key:"resetInitSegment",value:function(e,t,r,i,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(e,t,r,i),s.resetInitSegment(e,t,r,n))}},{key:"destroy",value:function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}},{key:"transmux",value:function(e,t,r,i,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)}},{key:"transmuxUnencrypted",value:function(e,t,r,i){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),a=n.audioTrack,s=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,t,r,!1,this.id),chunkMeta:i}}},{key:"transmuxSampleAes",value:function(e,t,r,i,n){var a=this;return this.demuxer.demuxSampleAes(e,t,r).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id),chunkMeta:n}})}},{key:"configureTransmuxer",value:function(e){for(var t,r=this.config,i=this.observer,n=this.typeSupported,a=0,s=$a.length;a<s;a++){var o;if(null!=(o=$a[a].demux)&&o.probe(e,this.logger)){t=$a[a];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,c=t.remux,d=t.demux;u&&u instanceof c||(this.remuxer=new c(i,r,n,this.logger)),l&&l instanceof d||(this.demuxer=new d(i,r,n,this.logger),this.probe=d.probe)}},{key:"needsProbing",value:function(e,t){return!this.demuxer||!this.remuxer||e||t}},{key:"getDecrypter",value:function(){var e=this.decrypter;return e||(e=this.decrypter=new Or(this.config)),e}}])}();var Za=function(e){return{remuxResult:{},chunkMeta:e}};function es(e){return"then"in e&&e.then instanceof Function}var ts=o(function e(t,r,i,n,s){a(this,e),this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=i,this.duration=n,this.defaultInitPts=s||null}),rs=o(function e(t,r,i,n,s,o){a(this,e),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=t,this.contiguous=r,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}),is=0,ns=function(){return o(function e(t,r,i,n){var s=this;a(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=is++,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=function(e){var t=e.data,r=s.hls;if(r&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var i,n=null==(i=s.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=s.frag,t.data.part=s.part,t.data.id=s.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(s.hls){var t=new Error("".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")"));s.hls.config.enableWorker=!1,s.hls.logger.warn('Error in "'.concat(s.id,'" Web Worker, fallback to inline')),s.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var o=t.config;this.hls=t,this.id=r,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;var l=function(e,t){(t=t||{}).frag=s.frag||void 0,e===ee.ERROR&&(t.parent=s.id,t.part=s.part,s.error=t.error),s.hls.trigger(e,t)};this.observer=new Pn,this.observer.on(ee.FRAG_DECRYPTED,l),this.observer.on(ee.ERROR,l);var u=Lt(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var c=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(c.log("loading Web Worker ".concat(o.workerPath,' for "').concat(r,'"')),this.workerContext=function(e){var t=Dn[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Dn[e]=i,i}(o.workerPath)):(c.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=function(){var e=Dn[xn];if(e)return e.clientCount++,e;var t=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}),r=self.URL.createObjectURL(t),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return Dn[xn]=i,i}());var d=this.workerContext.worker;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:r,config:Kt(o)})}catch(e){c.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),e),this.terminateWorker(),this.error=null,this.transmuxer=new Ja(this.observer,u,o,"",r,t.logger)}return}}this.transmuxer=new Ja(this.observer,u,o,"",r,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=is++;var t=this.hls.config,r=Lt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Kt(t)})}}},{key:"terminateWorker",value:function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=Dn[e||xn];if(t&&1===t.clientCount--){var r=t.worker,i=t.objectURL;delete Dn[e||xn],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}}},{key:"destroy",value:function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}},{key:"push",value:function(e,t,r,i,n,a,s,o,l,u){var c,d,h=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,v=this.transmuxer,g=a?a.start:n.start,p=n.decryptdata,m=this.frag,y=!(m&&n.cc===m.cc),E=!(m&&l.level===m.level),k=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===k&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!E&&(1===k||0===k&&(1===T||S&&T<=0)),A=self.performance.now();(E||k||0===n.stats.parsing.start)&&(n.stats.parsing.start=A),!a||!T&&b||(a.stats.parsing.start=A);var L=!(m&&(null==(c=n.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),I=new rs(y,b,o,E,g,L);if(!b||y||L){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for ".concat(n.type," sn: ").concat(l.sn).concat(l.part>-1?" part: "+l.part:""," ").concat(this.id===ae?"level":"track",": ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(y,"\n trackSwitch: ").concat(E,"\n contiguous: ").concat(b,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(L));var R=new ts(r,i,t,s,u);this.configureTransmuxer(R)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(v){var w=v.push(e,p,l,I);es(w)?w.then(function(e){h.handleTransmuxComplete(e)}).catch(function(e){h.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}},{key:"flush",value:function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);es(n)?n.then(function(r){t.handleFlushResult(r,e)}).catch(function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}},{key:"transmuxerError",value:function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}},{key:"handleFlushResult",value:function(e,t){var r=this;e.forEach(function(e){r.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),as=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"audio-stream-controller",se])).mainAnchor=null,s.mainFragLoading=null,s.audioOnly=!1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s.registerListeners(),s}return d(t,e),o(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),E(t,"onHandlerDestroying",this,3)([]),this.resetItem()}},{key:"resetItem",value:function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}},{key:"registerListeners",value:function(){E(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ee.BUFFER_RESET,this.onBufferReset,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ee.FRAG_LOADING,this.onFragLoading,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(E(t,"unregisterListeners",this,3)([]),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ee.BUFFER_RESET,this.onBufferReset,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this))}},{key:"onInitPtsFound",value:function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId;if(i===ae){var o=r.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:a,trackId:s},this.log("InitPTS for cc: ".concat(o," found from main: ").concat(n/a," (").concat(n,"/").concat(a,") trackId: ").concat(s)),this.mainAnchor=r,this.state===Tn){var u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==o)&&this.syncWithAnchor(r,null==u?void 0:u.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(r,l)):this.state===hn&&this.tick()}}},{key:"getLoadPosition",value:function(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:E(t,"getLoadPosition",this,3)([])}},{key:"syncWithAnchor",value:function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=ir(this.getLevelDetails(),n,this.getLoadPosition());a&&(this.log("Syncing with main frag at ".concat(a.start," cc ").concat(a.cc)),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===hn&&this.doTickIdle())}}},{key:"startLoad",value:function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=dn);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r,this.state=hn):this.state=pn,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"doTick",value:function(){switch(this.state){case hn:this.doTickIdle();break;case pn:var e=this.levels,r=this.trackId,i=null==e?void 0:e[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=Tn}break;case gn:this.checkRetryDate();break;case Tn:var a=this.waitingData;if(a){var s=a.frag,o=a.part,l=a.cache,u=a.complete,c=this.mainAnchor;if(void 0!==this.initPTS[s.cc]){this.waitingData=null,this.state=vn;var d={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),u&&E(t,"_handleFragmentLoadComplete",this,3)([d])}else c&&c.cc!==a.frag.cc&&this.syncWithAnchor(c,a.frag)}else this.state=hn}this.onTickEnd()}},{key:"resetLoadingState",value:function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),E(t,"resetLoadingState",this,3)([])}},{key:"onTickEnd",value:function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}},{key:"doTickIdle",value:function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=pn,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,De,se));var u=this.getFwdBufferInfo(l,se);if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(ee.BUFFER_EOS,{type:"audio"}),void(this.state=En);var c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,v=this.getLoadPosition(),g=this.flushing?v:u.end;if(this.switchingTrack&&i){var p=v;o.PTSKnown&&p<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var m=this.getNextFragment(g,o);if(m&&this.isLoopLoading(m,g)&&(m=this.getNextFragmentLoopLoading(m,o,u,ae,d)),m){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Oe(m)&&!m.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Lr&&(this.mainFragLoading=y=null),y&&Oe(y))){if(m.start>y.end){var E=this.fragmentTracker.getFragAtPos(g,ae);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,s,g)}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(e,r){this.bufferFlushed=this.flushing=!1,E(t,"onMediaDetaching",this,3)([e,r])}},{key:"onAudioTracksUpdated",value:function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map(function(e){return new Gt(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==dn&&(this.setInterval(100),this.state=hn,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}},{key:"onManifestLoading",value:function(){E(t,"onManifestLoading",this,3)([]),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ee.AUDIO_TRACK_LOADED,r))}},{key:"onAudioTrackLoaded",value:function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==dn&&(this.state=pn));this.cachedTrackLoadedData=null,this.log("Audio track ".concat(a,' "').concat(o.name,'" of "').concat(s,'" loaded [').concat(n.startSN,",").concat(n.endSN,"]").concat(n.lastPartSn?"[part-".concat(n.lastPartSn,"-").concat(n.lastPartIndex,"]"):"",",duration:").concat(n.totalduration));var u=i[a],c=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(n,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);n.alignedSliding||(sn(n,l),n.alignedSliding||on(n,l),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(ee.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==pn||this.waitForCdnTuneIn(n)||(this.state=hn),this.tick()}else this.warn("Audio tracks reset while loading track ".concat(a,' "').concat(o.name,'" of "').concat(s,'"'))}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var c=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new ns(this.hls,se,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){var v=i?i.index:-1,g=-1!==v,p=new Vr(r.level,r.sn,r.stats.chunkCount,n.byteLength,v,g);d.push(n,f,c,"",r,i,u.totalduration,!1,p,h)}else{this.log("Unknown video PTS for cc ".concat(r.cc,", waiting for video PTS before demuxing audio frag ").concat(r.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new Ln,complete:!1}).cache.push(new Uint8Array(n)),this.state!==dn&&(this.state=Tn)}}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"_handleFragmentLoadComplete",value:function(e){this.waitingData?this.waitingData.complete=!0:E(t,"_handleFragmentLoadComplete",this,3)([e])}},{key:"onBufferReset",value:function(){this.mediaBuffer=null}},{key:"onBufferCreated",value:function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}},{key:"onFragLoading",value:function(e,t){!this.audioOnly&&t.frag.type===ae&&Oe(t.frag)&&(this.mainFragLoading=t,this.state===hn&&this.tick())}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part;if(r.type===se)if(this.fragContextChanged(r))this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if(Oe(r)){this.fragPrevious=r;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},n)))}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==ae||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"onError",value:function(e,r){var i;if(r.fatal)this.state=kn;else switch(r.details){case Z.FRAG_GAP:case Z.FRAG_PARSING_ERROR:case Z.FRAG_DECRYPT_ERROR:case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(se,r);break;case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==pn||(null==(i=r.context)?void 0:i.type)!==ie||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case Z.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,E(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]));break;case Z.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==Ce&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==Ce){this.flushing=!1,this.bufferFlushed=!0,this.state===En&&(this.state=hn);var i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,r,se),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var t,r="audio",i=this.hls,n=e.remuxResult,a=e.chunkMeta,s=this.getCurrentContext(a);if(s){var o=s.frag,l=s.part,u=s.level,c=u.details,d=n.audio,h=n.text,f=n.id3,v=n.initSegment;if(!this.fragContextChanged(o)&&c){if(this.state=mn,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){var g=o.initSegment||o;if(this.unhandledEncryptionError(v,o))return;this._bufferInitSegment(u,v.tracks,g,a),i.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:r,tracks:v.tracks})}if(d){var p=d.startPTS,m=d.endPTS,y=d.startDTS,E=d.endDTS;l&&(l.elementaryStreams[De]={startPTS:p,endPTS:m,startDTS:y,endDTS:E}),o.setElementaryStreamInfo(De,p,m,y,E),this.bufferFragmentData(d,o,l,a)}if(null!=f&&null!=(t=f.samples)&&t.length){var k=de({id:r,frag:o,details:c},f);i.trigger(ee.FRAG_PARSING_METADATA,k)}if(h){var T=de({id:r,frag:o,details:c},h);i.trigger(ee.FRAG_PARSING_USERDATA,T)}}else this.fragmentTracker.removeFragment(o)}else this.resetWhenMissingContext(a)}},{key:"_bufferInitSegment",value:function(e,t,r,i){if(this.state===mn&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=se;var a=e.audioCodec;this.log("Init audio buffer, container:".concat(n.container,", codecs[level/parsed]=[").concat(a,"/").concat(n.codec,"]")),a&&1===a.split(",").length&&(n.levelCodec=a),this.hls.trigger(ee.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(ee.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,r,i){var n,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===Sr||a===Ar)if(Oe(e))if(null!=(n=r.details)&&n.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter ".concat(e.cc," of live stream before loading audio fragment ").concat(e.sn," of level ").concat(this.trackId)),this.state=Tn;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&on(r.details,s)}else E(t,"loadFragment",this,3)([e,r,i]);else this._loadInitSegment(e,r);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack){var r=this.bufferedTrack;zt({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},e,Xt)||($t(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),E(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]),this.bufferedTrack=null):this.bufferedTrack=e)}}},{key:"completeAudioSwitch",value:function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},e))}}])}(bn),ss=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r,e.logger])).hls=void 0,i.canLoad=!1,i.timer=-1,i.hls=e,i}return d(t,e),o(t,[{key:"destroy",value:function(){this.clearTimer(),this.hls=this.log=this.warn=null}},{key:"clearTimer",value:function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}},{key:"startLoad",value:function(){this.canLoad=!0,this.loadPlaylist()}},{key:"stopLoad",value:function(){this.canLoad=!1,this.clearTimer()}},{key:"switchParams",value:function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a<i.length;a++){var s=i[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: ".concat(e)),o=s.URI||""}if(o===e){n=a;break}o===e.substring(0,o.length)&&(n=a)}if(-1!==n){var l=i[n],u=parseInt(l["LAST-MSN"])||t.lastPartSn,c=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}var h=r&&Ut(r);return new Bt(u,c>=0?c:void 0,h)}}}},{key:"loadPlaylist",value:function(e){this.clearTimer()}},{key:"loadingPlaylist",value:function(e,t){this.clearTimer()}},{key:"shouldLoadPlaylist",value:function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}},{key:"getUrlWithDirectives",value:function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(e))}return e}},{key:"playlistLoaded",value:function(e,t,r){var i=t.details,n=t.stats,a=self.performance.now(),s=n.loading.first?Math.max(0,a-n.loading.first):0;i.advancedDateTime=Date.now()-s;var o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){var l=Math.max(o||0,0);i.appliedTimelineOffset=l,i.fragments.forEach(function(e){e.setStart(e.playlistOffset+l)})}if(i.live||null!=r&&r.live){var u="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(r),r&&i.fragments.length>0){Yi(r,i,this);var c=i.playlistParsingError;if(c){this.warn(c);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var h,f=t.networkDetails;return void d.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:c,reason:c.message,level:t.level||void 0,parent:null==(h=i.fragments[0])?void 0:h.type,networkDetails:f,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var v,g=this.hls.mainForwardBufferInfo,p=g?g.end-g.len:0,m=Xi(i,1e3*(i.edge-p));if(i.requestScheduled+m<a?i.requestScheduled=a:i.requestScheduled+=m,this.log("live playlist ".concat(e," ").concat(i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED")),!this.canLoad||!i.live)return;var y=void 0,E=void 0;if(i.canBlockReload&&i.endSN&&i.advanced){var k=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,b=i.lastPartIndex,A=T===S;-1!==b?A?(y=S+1,E=k?0:b):(y=T,E=k?b+1:i.maxPartIndex):y=S+1;var L=i.age,I=L+i.ageHeader,R=Math.min(I-i.partTarget,1.5*i.targetduration);if(R>0){if(I>3*i.targetduration)this.log("Playlist last advanced ".concat(L.toFixed(2),"s ago. Omitting segment and part directives.")),y=void 0,E=void 0;else if(null!=r&&r.tuneInGoal&&I-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(r.tuneInGoal," to: ").concat(R," with playlist age: ").concat(i.age)),R=0;else{var w=Math.floor(R/i.targetduration);if(y+=w,void 0!==E)E+=Math.round(R%i.targetduration/i.partTarget);this.log("CDN Tune-in age: ".concat(i.ageHeader,"s last advanced ").concat(L.toFixed(2),"s goal: ").concat(R," skip sn ").concat(w," to part ").concat(E))}i.tuneInGoal=R}if(v=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),k||!A)return i.requestScheduled=a,void this.loadingPlaylist(u,v)}else(i.canBlockReload||i.canSkipUntil)&&(v=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));v&&void 0!==y&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(m-2*s,m/2)),this.scheduleLoading(u,v,i)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s)this.loadingPlaylist(e,t);else{var o=s-a;this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(function(){return i.loadingPlaylist(e,t)},o)}}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,r,i){var n=Ut(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=Ot),new Bt(r,i,n)}},{key:"checkRetry",value:function(e){var t=this,r=e.details,i=nr(e),n=e.errorAction,a=n||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,c=!!n&&!!u&&(s===gr||!n.resolved&&s===fr);if(c){var d;if(l>=u.maxNumRetry)return!1;if(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" without delivery-directives')),this.loadPlaylist();else{var h=lr(u,l);this.clearTimer(),this.timer=self.setTimeout(function(){return t.loadPlaylist()},h),this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" in ').concat(h,"ms"))}e.levelRetry=!0,n.resolved=!0}return c}}])}(ve);function os(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!ls(e[r].attrs,t[r].attrs))return!1;return!0}function ls(e,t,r){var i=e["STABLE-RENDITION-ID"];return i&&!r?i===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(r){return e[r]!==t[r]})}function us(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var cs=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e,"audio-track-controller"])).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,E(t,"destroy",this,3)([])}},{key:"onManifestLoading",value:function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.audioTracks||[]}},{key:"onAudioTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Audio track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.audioPreference;if(!n&&s){var o=qt(s,a,Xt);if(o>-1)n=a[o];else{var l=qt(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={audioTracks:a};this.log("Updating audio tracks, ".concat(a.length," track(s) found in group(s): ").concat(null==r?void 0:r.join(","))),this.hls.trigger(ee.AUDIO_TRACKS_UPDATED,c);var d=this.trackId;if(-1!==u&&-1===d)this.setAudioTrack(u);else if(a.length&&-1===d){var h,f=new Error("No audio track selected for current audio group-ID(s): ".concat(null==(h=this.groupIds)?void 0:h.join(",")," track count: ").concat(a.length));this.warn(f.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&(t.context.type!==ie||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}},{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}},{key:"setAudioOption",value:function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&zt(e,i,Xt))return i;var n=qt(e,this.tracksInGroup,Xt);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce(function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e},{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),c=Qt(t,i,function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter(function(e){return!i||-1!==i.indexOf(e.groupId)});return qt(e,a,n)>-1});return c>-1?c:Qt(t,i,function(t){var i=t.audioGroups,a=r.filter(function(e){return!i||-1!==i.indexOf(e.groupId)});return qt(e,a,n)>-1})}(e,t.levels,r,s,Xt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=qt(e,r);if(l>-1)return r[l]}}}return null}},{key:"setAudioTrack",value:function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: ".concat(e));else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e],n=i.details&&!i.details.live;if(!(e===this.trackId&&i===r&&n||(this.log("Switching to audio-track ".concat(e,' "').concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId," channels:").concat(i.channels)),this.trackId=e,this.currentTrack=i,this.hls.trigger(ee.AUDIO_TRACK_SWITCHING,fe({},i)),n))){var a=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(a)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||zt(e,i,Xt)))return r}if(e){for(var n=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,c=0;c<t.length;c++){if(zt({name:n,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[c],Xt))return c}for(var d=0;d<t.length;d++){var h=t[d];if(ls(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var v=t[f];if(ls(e.attrs,v.attrs,["LANGUAGE"]))return f}}return-1}},{key:"loadPlaylist",value:function(e){E(t,"loadPlaylist",this,3)([]);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&$t(r.url,this.hls)&&this.scheduleLoading(r,e)}},{key:"loadingPlaylist",value:function(e,r){E(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ee.AUDIO_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}}])}(ss),ds=function(){return o(function e(t){a(this,e),this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t},[{key:"destroy",value:function(){this.tracks=this.queues=null}},{key:"append",value:function(e,t,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(e[0].execute(),e.splice(0,1))})}},{key:"unblockAudio",value:function(e){null!==this.queues&&(this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio"))}},{key:"executeNext",value:function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var n=null==(i=this.tracks[e])?void 0:i.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}}},{key:"shiftAndExecuteNext",value:function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}},{key:"current",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}},{key:"toString",value:function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}},{key:"list",value:function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer".concat(i.updating?" updating":"").concat(r.ended?" ended":"").concat(r.ending?" ending":""):"none"}},{key:"listOps",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e].map(function(e){return e.label}).join(", "))||""}}])}(),hs=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,fs="HlsJsTrackRemovedError",vs=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e])).name=fs,r}return d(t,e),o(t)}(L(Error)),gs=function(e){function t(e,r){var i,s;return a(this,t),(i=n(this,t,["buffer-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.blockedAudioAppend=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(n.removeEventListener("sourceopen",i._onMediaSourceOpen),r.removeEventListener("emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(ee.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){i.log("Media source closed")},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource (".concat(r," > ").concat(t,")"))},i.hls=e,i.fragmentTracker=r,i.appendSource=(s=Te(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}return d(t,e),o(t,[{key:"hasSourceTypes",value:function(){return Object.keys(this.tracks).length>0}},{key:"destroy",value:function(){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}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.BUFFER_RESET,this.onBufferReset,this),e.on(ee.BUFFER_APPENDING,this.onBufferAppending,this),e.on(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ee.BUFFER_EOS,this.onBufferEos,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.FRAG_PARSED,this.onFragParsed,this),e.on(ee.FRAG_CHANGED,this.onFragChanged,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.BUFFER_RESET,this.onBufferReset,this),e.off(ee.BUFFER_APPENDING,this.onBufferAppending,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.BUFFER_EOS,this.onBufferEos,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.FRAG_PARSED,this.onFragParsed,this),e.off(ee.FRAG_CHANGED,this.onFragChanged,this),e.off(ee.ERROR,this.onError,this)}},{key:"transferMedia",value:function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var a=this.isQueued();(n||a)&&this.warn("Transfering MediaSource with".concat(a?" operations in queue":"").concat(n?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}var s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===r?de(i,s.tracks):this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];r&&(i[r]=de({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null}),{media:t,mediaSource:r,tracks:i}}},{key:"initTracks",value:function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}},{key:"onManifestLoading",value:function(){this.bufferCodecEventsTotal=0,this.details=null}},{key:"onManifestParsed",value:function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log("".concat(i," bufferCodec event(s) expected.")),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=Te(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,ps(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}r.addEventListener("emptied",this._onMediaEmptied)}}},{key:"assignMediaSource",value:function(e){var t,r;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(r=e.constructor)?void 0:r.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))}},{key:"attachTransferred",value:function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then(function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()})};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(Kt(i,function(e,t){return"initSegment"===e?void 0:t}),";\ntransfer tracks: ").concat(Kt(n,function(e,t){return"initSegment"===e?void 0:t}),"}")),!Se(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,c=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return c-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(l," -> ").concat(c)):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(n),'"->"').concat(Object.keys(i),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(ee.MEDIA_DETACHING,{}),this.onMediaAttaching(ee.MEDIA_ATTACHING,r),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=jr.getBuffered(a);s.detectEvictedFragments(r,l,o,null,!0)}var u=ms(r),c=[r,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}}},{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"onMediaDetaching",value:function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source ".concat(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(function(e){var t=m(e,1)[0];t&&r.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: ".concat(e.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}a.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("sourceended",this._onMediaSourceEnded),a.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.removeEventListener("startstreaming",this._onStartStreaming),a.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&ps(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(ee.MEDIA_DETACHED,t)}},{key:"onBufferReset",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];r&&e.resetBuffer(r)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset ".concat(e),t)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[ms(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)}},{key:"resetQueue",value:function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new ds(this.tracks)}},{key:"onBufferCodecs",value:function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(a,'" (current SB count ').concat(this.sourceBufferCount,")"));var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some(function(e){return!n[e]});s||o?this.warn('Unsupported transition between "'.concat(Object.keys(n),'" and "').concat(a,'" SourceBuffers')):(a.forEach(function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,c=s.container,d=s.metadata,h=s.supplemental,f=n[e],v=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;f||(f=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:h,container:c,levelCodec:u,metadata:d,id:o});var y=St(p,m),E=null==y?void 0:y.replace(hs,"$1"),k=St(l,u),T=null==(a=k)?void 0:a.replace(hs,"$1");k&&y&&E!==T&&("audio"===e.slice(0,5)&&(k=Tt(k,i.appendSource)),i.log("switching codec ".concat(p," to ").concat(k)),k!==(f.pendingCodec||f.codec)&&(f.pendingCodec=k),f.container=c,i.appendChangeType(e,c,k))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,r){var i=this,n="".concat(t,";codecs=").concat(r),a={label:"change-type=".concat(n),execute:function(){var a=i.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(i.log("changing ".concat(e," sourceBuffer type to ").concat(n)),s.changeType(n),a.codec=r,a.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change ".concat(e," SourceBuffer type"),t)}};this.append(a,e,this.isPending(this.tracks[e]))}},{key:"blockAudio",value:function(e){var t,r=this,i=e.start,n=i+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,ae))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t=r.tracks.video;(r.lastVideoAppendEnd>n||null!=t&&t.buffer&&jr.isBuffered(t.buffer,n)||!0===(null==(e=r.fragmentTracker.getAppendedFrag(n,ae))?void 0:e.gap))&&(r.blockedAudioAppend=null,r.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}}},{key:"unblockAudio",value:function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}},{key:"onBufferAppending",value:function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,c=t.offset,d=u.buffering[a],h=o.sn,f=o.cc,v=self.performance.now();d.start=v;var g=o.stats.buffering,p=l?l.stats.buffering:null;0===g.start&&(g.start=v),p&&0===p.start&&(p.start=v);var y=i.audio,E=!1;"audio"===a&&"audio/mpeg"===(null==y?void 0:y.container)&&(E=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var k=i.video,T=null==k?void 0:k.buffer;if(T&&"initSegment"!==h){var S=l||o,b=this.blockedAudioAppend;if("audio"!==a||"main"===s||this.blockedAudioAppend||k.ending||k.ended){if("video"===a){var A=S.end;if(b){var L=b.frag.start;(A>L||A<this.lastVideoAppendEnd||jr.isBuffered(T,L))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}else{var I=S.start+.05*S.duration,R=T.buffered,w=this.currentOp("video");R.length||w?!w&&!jr.isBuffered(T,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(S):this.blockAudio(S)}}var P=(l||o).start,x={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(E?r.updateTimestampOffset(t,P,.1,a,h,f):void 0!==c&&X(c)&&r.updateTimestampOffset(t,c,1e-6,a,h,f)),r.appendExecutor(n,a)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);var t={};r.sourceBuffers.forEach(function(e){var r=m(e,2),i=r[0],n=r[1];i&&(t[i]=jr.getBuffered(n))}),r.appendErrors[a]=0,"audio"===a||"video"===a?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(ee.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:o.type,timeRanges:t})},onError:function(e){var t,i={type:J.MEDIA_ERROR,parent:o.type,details:Z.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},n=null==(t=r.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=Z.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&r.mediaSourceOpenOrEnded&&!n)i.errorAction=Tr(!0);else if(e.name===fs&&0===r.sourceBufferCount)i.errorAction=Tr(!0);else{var s=++r.appendErrors[a];r.warn("Failed ".concat(s,"/").concat(r.hls.config.appendErrorMaxRetry,' times to append segment in "').concat(a,'" sourceBuffer (').concat(n||"no media error",")")),(s>=r.hls.config.appendErrorMaxRetry||n)&&(i.fatal=!0)}r.hls.trigger(ee.ERROR,i)}};this.log('queuing "'.concat(a,'" append sn: ').concat(h).concat(l?" p: "+l.index:""," of ").concat(o.type===ae?"level":"track"," ").concat(o.level," cc: ").concat(f)),this.append(x,a,this.isPending(this.tracks[a]))}},{key:"getFlushOp",value:function(e,t,r){var i=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(r)),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){i.hls.trigger(ee.BUFFER_FLUSHED,{type:e})},onError:function(n){i.warn("Failed to remove ".concat(t,"-").concat(r,' from "').concat(e,'" SourceBuffer'),n)}}}},{key:"onBufferFlushing",value:function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach(function(e){var t=m(e,1)[0];t&&r.append(r.getFlushOp(t,n,a),t)})}},{key:"onFragParsed",value:function(e,t){var r=this,i=t.frag,n=t.part,a=[],s=n?n.elementaryStreams:i.elementaryStreams;s[_e]?a.push("audiovideo"):(s[De]&&a.push("audio"),s[Ce]&&a.push("video"));0===a.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(i.type," level: ").concat(i.level," sn: ").concat(i.sn)),this.blockBuffers(function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.hls.trigger(ee.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type})},a).catch(function(e){r.warn("Fragment buffered callback ".concat(e)),r.stepOperationQueue(r.sourceBufferTypes)})}},{key:"onFragChanged",value:function(e,t){this.trimBuffers()}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some(function(t){var r=m(t,1)[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var r,i=this;this.sourceBuffers.forEach(function(e){var r=m(e,1)[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log("".concat(r," buffer reached EOS"))))}});var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,r=m(e,1)[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(function(){i.tracksEnded();var e=i.mediaSource;e&&"open"===e.readyState?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(ee.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(e.readyState))})):(this.tracksEnded(),this.hls.trigger(ee.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}},{key:"tracksEnded",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())}},{key:"updateDuration",value:function(){var e=this;this.blockUntilOpen(function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)})}},{key:"onError",value:function(e,t){if(t.details===Z.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;X(i)&&i!==t.frag.level&&this.resetAppendErrors()}}},{key:"resetAppendErrors",value:function(){this.appendErrors={audio:0,video:0,audiovideo:0}}},{key:"trimBuffers",value:function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.sourceBufferCount){var i=e.config,n=r.currentTime,a=t.levelTargetDuration,s=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(X(s)&&s>=0){var o=Math.max(s,a),l=Math.floor(n/a)*a-o;this.flushBackBuffer(n,a,l)}var u=i.frontBufferFlushThreshold;if(X(u)&&u>0){var c=Math.max(i.maxBufferLength,u),d=Math.max(c,a),h=Math.floor(n/a)*a+d;this.flushFrontBuffer(n,a,h)}}}},{key:"flushBackBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(e){var t=m(e,2),n=t[0],a=t[1];if(a){var s=jr.getBuffered(a);if(s.length>0&&r>s.start(0)){var o;i.hls.trigger(ee.BACK_BUFFER_REACHED,{bufferEnd:r});var l=i.tracks[n];if(null!=(o=i.details)&&o.live)i.hls.trigger(ee.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=l&&l.ended)return void i.log("Cannot flush ".concat(n," back buffer while SourceBuffer is in ended state"));i.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}},{key:"flushFrontBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(t){var n=m(t,2),a=n[0],s=n[1];if(s){var o=jr.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(r>u||e>=u&&e<=c)return;i.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return X(a)?{duration:a}:null;var s=this.media.duration;return i>(X(r.duration)?r.duration:0)&&i>s||!X(s)?{duration:i}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==t&&(X(t)&&this.log("Updating MediaSource duration to ".concat(t.toFixed(3))),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to ".concat(n.duration,". Setting seekable range to ").concat(r,"-").concat(i,".")),n.setLiveSeekableRange(r,i)))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"checkPendingTracks",value:function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(Kt(r))),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}},{key:"bufferCreated",value:function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach(function(r){var i=m(r,2),n=i[0],a=i[1];if(n){var s=e.tracks[n];t[n]={buffer:a,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(ee.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];e.executeNext(r)})}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o="".concat(a.container,";codecs=").concat(s);a.codec=s,this.log("creating sourceBuffer(".concat(o,")").concat(this.currentOp(n)?" Queued":""," ").concat(Kt(a)));try{var l=r.addSourceBuffer(o),u=ms(n),c=[n,l];t[u]=c,a.buffer=l}catch(e){var d;return this.error("error while trying to add sourceBuffer: ".concat(e.message)),this.shiftAndExecuteNext(n),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[n],void this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}},{key:"getTrackCodec",value:function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&vt(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n<i.length;n++)ft(i[n],"video")||r.push(i[n]);return t&&r.push(t),r.join(",")}(i,r));var n=St(i,e.levelCodec);return n?"audio"===t.slice(0,5)?Tt(n,this.appendSource):n:""}},{key:"trackSourceBuffer",value:function(e,t){var r=this,i=t.buffer;if(i){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,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",function(e,t){var i=t.removedRanges;null!=i&&i.length&&r.hls.trigger(ee.BUFFER_FLUSHED,{type:e})})}}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"onSBUpdateStart",value:function(e){var t=this.currentOp(e);t&&t.onStart()}},{key:"onSBUpdateEnd",value:function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var r,i=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(null==(r=this.mediaSource)?void 0:r.readyState));this.error("".concat(i),t),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var n=this.currentOp(e);n&&n.onError(i)}},{key:"updateTimestampOffset",value:function(e,t,r,i,n,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating ".concat(i," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(n," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)return this.warn("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist")),void this.shiftAndExecuteNext(e);var o=X(i.duration)?i.duration:1/0,l=X(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(r,o,l);c>u&&(!a.ending||a.ended)?(a.ended=!1,this.log("Removing [".concat(u,",").concat(c,"] from the ").concat(e," SourceBuffer")),s.remove(u,c)):this.shiftAndExecuteNext(e)}},{key:"appendExecutor",value:function(e,t){var r=this.tracks[t],i=null==r?void 0:r.buffer;if(!i)throw new vs("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));r.ending=!1,r.ended=!1,i.appendBuffer(e)}},{key:"blockUntilOpen",value:function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(function(e){t.warn("SourceBuffer blocked callback ".concat(e)),t.stepOperationQueue(t.sourceBufferTypes)});else try{e()}catch(e){this.warn("Callback run without blocking ".concat(this.operationQueue," ").concat(e))}}},{key:"isUpdating",value:function(){return this.sourceBuffers.some(function(e){var t=m(e,2),r=t[0],i=t[1];return r&&i.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var r=m(t,1)[0];return r&&!!e.currentOp(r)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"blockBuffers",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=r.map(function(e){return t.appendBlocker(e)});return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(function(r){i===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;i&&!i.updating&&t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}},{key:"appendBlocker",value:function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}},{key:"currentOp",value:function(e){return this.operationQueue?this.operationQueue.current(e):null}},{key:"executeNext",value:function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}},{key:"shiftAndExecuteNext",value:function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){return t+(e.isPending(e.tracks[r])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(m(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return m(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach(function(e){r.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}}])}(ve);function ps(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function ms(e){return"audio"===e?1:0}var ys=function(){function e(t){a(this,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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}return o(e,[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"destroy",value:function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListener",value:function(){var e=this.hls;e.off(ee.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"onFpsDropLevelCapping",value:function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}},{key:"onManifestParsed",value:function(e,t){var r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}},{key:"onLevelsUpdated",value:function(e,t){this.timer&&X(this.autoLevelCapping)&&this.detectPlayerSize()}},{key:"onBufferCodecs",value:function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}},{key:"onMediaDetaching",value:function(){this.stopCapping(),this.media=null}},{key:"detectPlayerSize",value:function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(r,": ").concat(e[r].height,"p@").concat(e[r].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter(function(e,i){return r.isLevelAllowed(e)&&i<=t});return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}},{key:"startCapping",value:function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}},{key:"stopCapping",value:function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}},{key:"getDimensions",value:function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}},{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}},{key:"isLevelAllowed",value:function(e){return!this.restrictedLevels.some(function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height})}}],[{key:"getMaxLevelByMediaSize",value:function(e,t,r){if(null==e||!e.length)return-1;for(var i=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=Math.max(t,r),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&i(o,e[s+1])){n=s;break}}return n}}])}(),Es={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ks={HLS:"h"},Ts=o(function e(t,r){a(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=r});function Ss(e,t,r,i){return new Error("failed to ".concat(e,' "').concat((n=t,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"===S(n)?JSON.stringify(n):String(n)),'" as ').concat(r),{cause:i});var n}function bs(e,t,r){return Ss("serialize",e,t,r)}var As=o(function e(t){a(this,e),this.description=t}),Ls="Bare Item";function Is(e){if(!1===ArrayBuffer.isView(e))throw bs(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,k(t)))),":");var t}function Rs(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw bs(e,"Integer");return e.toString()}function ws(e,t){if(e<0)return-ws(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var i=Math.floor(e*r);return(i%2==0?i:i+1)/r}return Math.round(e*r)/r}function Ps(e){var t=ws(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw bs(e,"Decimal");var r=t.toString();return r.includes(".")?r:"".concat(r,".0")}var xs=/[\x00-\x1f\x7f]+/;function Ds(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw bs(r,"Token");return r}function Cs(e){switch(S(e)){case"number":if(!X(e))throw bs(e,Ls);return Number.isInteger(e)?Rs(e):Ps(e);case"string":return function(e){if(xs.test(e))throw bs(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return Ds(e);case"boolean":return function(e){if("boolean"!=typeof e)throw bs(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@".concat(Rs(e.getTime()/1e3))}(e);if(e instanceof Uint8Array)return Is(e);if(e instanceof As)return Ds(e);default:throw bs(e,Ls)}}function _s(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw bs(e,"Key");return e}function Ms(e){return null==e?"":Object.entries(e).map(function(e){var t=m(e,2),r=t[0],i=t[1];return!0===i?";".concat(_s(r)):";".concat(_s(r),"=").concat(Cs(i))}).join("")}function Os(e){return e instanceof Ts?"".concat(Cs(e.value)).concat(Ms(e.params)):Cs(e)}function Fs(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==S(e)||null==e)throw bs(e,"Dict");var r=e instanceof Map?e.entries():Object.entries(e),i=(null==t?void 0:t.whitespace)?" ":"";return Array.from(r).map(function(e){var t=m(e,2),r=t[0],i=t[1];i instanceof Ts==!1&&(i=new Ts(i));var n,a=_s(r);return!0===i.value?a+=Ms(i.params):(a+="=",Array.isArray(i.value)?a+="(".concat((n=i).value.map(Os).join(" "),")").concat(Ms(n.params)):a+=Os(i)),a}).join(",".concat(i))}function Ns(e,t){return Fs(e,t)}var Us="CMCD-Object",Bs="CMCD-Request",Gs="CMCD-Session",Hs="CMCD-Status",Vs={br:Us,ab:Us,d:Us,ot:Us,tb:Us,tpb:Us,lb:Us,tab:Us,lab:Us,url:Us,pb:Bs,bl:Bs,tbl:Bs,dl:Bs,ltc:Bs,mtp:Bs,nor:Bs,nrr:Bs,rc:Bs,sn:Bs,sta:Bs,su:Bs,ttfb:Bs,ttfbb:Bs,ttlb:Bs,cmsdd:Bs,cmsds:Bs,smrt:Bs,df:Bs,cs:Bs,ts:Bs,cid:Gs,pr:Gs,sf:Gs,sid:Gs,st:Gs,v:Gs,msd:Gs,bs:Hs,bsd:Hs,cdn:Hs,rtp:Hs,bg:Hs,pt:Hs,ec:Hs,e:Hs},Ks=Bs;function js(e,t){var r={};if(!e)return r;var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce(function(e,t){var r;return null===(r=i[t])||void 0===r||r.forEach(function(r){return e[r]=t}),e},{})):{};return n.reduce(function(t,r){var i,n=Vs[r]||a[r]||Ks;return(null!==(i=t[n])&&void 0!==i?i:t[n]={})[r]=e[r],t},r)}var Ys="event";var Ws=function(e){return Math.round(e)},qs=function(e,t){return Array.isArray(e)?e.map(function(e){return qs(e,t)}):e instanceof Ts&&"string"==typeof e.value?new Ts(qs(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1);n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+r.search+r.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},zs=function(e){return 100*Ws(e/100)},Xs={br:Ws,d:Ws,bl:zs,dl:zs,mtp:zs,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof Ts&&"string"==typeof e.value?r=new Ts([e]):"string"==typeof e&&(r=[e])),qs(r,t)},rtp:zs,tb:Ws},Qs="request",$s="response",Js=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Zs=["e"],eo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function to(e){return eo.test(e)}var ro=["d","dl","nor","ot","rtp","su"];var io=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];var no=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ao(e){return no.includes(e)||to(e)}var so=l(l(l({},$s,function(e){return Js.includes(e)||ro.includes(e)||io.includes(e)||to(e)}),Ys,function(e){return Js.includes(e)||Zs.includes(e)||to(e)}),Qs,function(e){return Js.includes(e)||ro.includes(e)||to(e)});function oo(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(null==e||"object"!==S(e))return r;var i=t.version||e.v||1,n=t.reportingMode||Qs,a=1===i?ao:so[n],s=Object.keys(e).filter(a),o=t.filter;"function"==typeof o&&(s=s.filter(o));var l=n===$s||n===Ys;l&&!s.includes("ts")&&s.push("ts"),i>1&&!s.includes("v")&&s.push("v");var u=de({},Xs,t.formatters),c={version:i,reportingMode:n,baseUrl:t.baseUrl};return s.sort().forEach(function(t){var n=e[t],a=u[t];if("function"==typeof a&&(n=a(n,c)),"v"===t){if(1===i)return;n=i}"pr"==t&&1===n||(l&&"ts"===t&&!X(n)&&(n=Date.now()),function(e){return"number"==typeof e?X(e):null!=e&&""!==e&&!1!==e}(n)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof n&&(n=new As(n)),r[t]=n))}),r}function lo(e,t,r){return de(e,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(!e)return r;var i=js(oo(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(i).reduce(function(e,t){var r=m(t,2),i=r[0],n=Ns(r[1],{whitespace:!1});return n&&(e[i]=n),e},r)}(t,r))}function uo(e){if(!e)return"";var t=function(e){return e?Ns(oo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),{whitespace:!1}):""}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return encodeURIComponent(t)}var co=/CMCD=[^&#]+/;function ho(e,t,r){var i=function(e){if(!e)return"";var t=uo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return"".concat("CMCD","=").concat(t)}(t,r);if(!i)return e;if(co.test(e))return e.replace(co,i);var n=e.includes("?")?"&":"?";return"".concat(e).concat(n).concat(i)}var fo=function(){return o(function e(t){var r=this;a(this,e),this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0),r.buffering=!0},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1},this.applyPlaylistData=function(e){try{r.apply(e,{ot:Es.MANIFEST,su:!r.initialized})}catch(e){r.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var t=e.frag,i=e.part,n=r.hls.levels[t.level],a=r.getObjectType(t),s={d:1e3*(i||t).duration,ot:a};a!==Es.VIDEO&&a!==Es.AUDIO&&a!=Es.MUXED||(s.br=n.bitrate/1e3,s.tb=r.getTopBandwidth(a)/1e3,s.bl=r.getBufferLength(a));var o=i?r.getNextPart(i):r.getNextFrag(t);null!=o&&o.url&&o.url!==t.url&&(s.nor=o.url),r.apply(e,s)}catch(e){r.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=t;var i=this.config=t.config,n=i.cmcd;null!=n&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.sessionId,this.cid=n.contentId,this.useHeaders=!0===n.useHeaders,this.includeKeys=n.includeKeys,this.registerListeners())},[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}},{key:"onMediaDetached",value:function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}},{key:"onBufferCreated",value:function(e,t){var r,i;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer}},{key:"createData",value:function(){var e;return{v:1,sf:ks.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}},{key:"apply",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};de(t,this.createData());var r=t.ot===Es.INIT||t.ot===Es.VIDEO||t.ot===Es.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var i=this.includeKeys;i&&(t=Object.keys(t).reduce(function(e,r){return i.includes(r)&&(e[r]=t[r]),e},{}));var n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),lo(e.headers,t,n)):e.url=ho(e.url,t,n)}},{key:"getNextFrag",value:function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}}},{key:"getNextPart",value:function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}}},{key:"getObjectType",value:function(e){var t=e.type;return"subtitle"===t?Es.TIMED_TEXT:"initSegment"===e.sn?Es.INIT:"audio"===t?Es.AUDIO:"main"===t?this.hls.audioTracks.length?Es.VIDEO:Es.MUXED:void 0}},{key:"getTopBandwidth",value:function(e){var t,r=0,i=this.hls;if(e===Es.AUDIO)t=i.audioTracks;else{var n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;t=i.levels.slice(0,a)}return t.forEach(function(e){e.bitrate>r&&(r=e.bitrate)}),r>0?r:NaN}},{key:"getBufferLength",value:function(e){var t=this.media,r=e===Es.AUDIO?this.audioBuffer:this.videoBuffer;return r&&t?1e3*jr.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len:NaN}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,r=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}}])}(),vo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["content-steering",e.logger])).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=e,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.ERROR,this.onError,this))}},{key:"pathways",value:function(){return(this.levels||[]).reduce(function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e},[])}},{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}},{key:"startLoad",value:function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}},{key:"stopLoad",value:function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}},{key:"clearTimeout",value:function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"removeLevel",value:function(e){var t=this.levels;t&&(this.levels=t.filter(function(t){return t!==e}))}},{key:"onManifestLoading",value:function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}},{key:"onManifestParsed",value:function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}},{key:"onError",value:function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===fr&&r.flags===mr){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a),t.details!==Z.BUFFER_APPEND_ERROR||t.fatal?r.resolved||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(i?i.length:i," priorities: ").concat(Kt(n)," penalized: ").concat(Kt(this.penalizedPathways))):r.resolved=!0}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(r,'"')),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}},{key:"getLevelsForPathway",value:function(e){return null===this.levels?[]:this.levels.filter(function(t){return e===t.pathwayId})}},{key:"updatePathwayPriority",value:function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(function(e){i-r[e]>3e5&&delete r[e]});for(var n=0;n<e.length;n++){var a=e[n];if(!(a in r)){if(a===this.pathwayId)return;var s=this.hls.nextLoadLevel,o=this.hls.levels[s];if((t=this.getLevelsForPathway(a)).length>0){this.log('Setting Pathway to "'.concat(a,'"')),this.pathwayId=a,Zi(t),this.hls.trigger(ee.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(o.bitrate," to ").concat(l.bitrate)),this.hls.nextLoadLevel=s);break}}}}},{key:"getPathwayForGroupId",value:function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n<i.length;n++)if(t===ie&&i[n].hasAudioGroup(e)||t===ne&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return r}},{key:"clonePathways",value:function(e){var t=this,r=this.levels;if(r){var i={},n={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new Jr(e.attrs);t["PATHWAY-ID"]=a;var r=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);r&&(i[t.AUDIO]=r,t.AUDIO=r),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=po(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new Gt({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(var c=1;c<e.audioGroups.length;c++)u.addGroupId("audio","".concat(e.audioGroups[c],"_clone_").concat(a));if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)u.addGroupId("text","".concat(e.subtitleGroups[d],"_clone_").concat(a));return u});r.push.apply(r,k(l)),go(t.audioTracks,i,o,a),go(t.subtitleTracks,n,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,r=this,i=this.hls.config,n=i.loader;this.loader&&this.loader.destroy(),this.loader=new n(i);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: ".concat(e))}if("data:"!==t.protocol){var a=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+a)}var s={responseType:"json",url:t.href},o=i.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:function(e,i,n,a){r.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}r.scheduleRefresh(r.uri||n.url),l&&r.clonePathways(l);var c={steeringManifest:s,url:t.toString()};r.hls.trigger(ee.STEERING_MANIFEST_LOADED,c),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,i,n){if(r.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest (".concat(t.url,")")),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var r,i=null==(r=t.hls)?void 0:r.media;!i||i.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},r)}}])}(ve);function go(e,t,r,i){e&&Object.keys(t).forEach(function(n){var a=e.filter(function(e){return e.groupId===n}).map(function(e){var a=de({},e);return a.details=void 0,a.attrs=new Jr(a.attrs),a.url=a.attrs.URI=po(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=i,a});e.push.apply(e,k(a))})}function po(e,t,r,i){var n,a=i.HOST,s=i.PARAMS,o=i[r];t&&(n=null==o?void 0:o[t])&&(e=n);var l=new self.URL(e);return a&&!n&&(l.host=a),s&&Object.keys(s).sort().forEach(function(e){e&&l.searchParams.set(e,s[e])}),l.href}var mo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["eme",e.logger])).hls=void 0,r.config=void 0,r.media=null,r.mediaResolved=void 0,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.bannedKeyIds={},r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,n='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(r.debug(n),null!==i){if(!r.keyFormatPromise){var a=Object.keys(r.keySystemAccessPromises);a.length||(a=Ei(r.config));var s=a.map(yi).filter(function(e){return!!e});r.keyFormatPromise=r.getKeyFormatPromise(s)}r.keyFormatPromise.then(function(a){var s=mi(a);if("sinf"===t&&s===hi.FAIRPLAY){var o;try{var l=Ve(new Uint8Array(i)),u=rt(oi(JSON.parse(l).sinf));if(!u)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(u.subarray(8,24))}catch(e){return void r.warn("".concat(n," Failed to parse sinf: ").concat(e))}for(var c,d=Ae(o),h=r,f=h.keyIdToKeySessionPromise,v=h.mediaKeySessions,g=f[d],p=function(){var e=v[m],n=e.decryptdata;if(!n.keyId)return 0;var a=Ae(n.keyId);return ii(o,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(d)?(g=f[a])?(n.pssh||(delete f[a],n.pssh=new Uint8Array(i),n.keyId=o,(g=f[d]=g.then(function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")})).catch(function(e){return r.handleError(e)})),1):0:void 0},m=0;m<v.length&&(0===(c=p())||1!==c);m++);g||r.handleError(new Error("Key ID ".concat(d," not encountered in playlist. Key-system sessions ").concat(v.length,".")))}else r.log('Ignoring "'.concat(e.type,'" event with init data type: "').concat(t,'" for selected key-system ').concat(s))}).catch(function(e){return r.handleError(e)})}},r.onWaitingForKey=function(e){r.log('"'.concat(e.type,'" event'))},r.hls=e,r.config=e.config,r.registerListeners(),r}return d(t,e),o(t,[{key:"destroy",value:function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}},{key:"registerListeners",value:function(){this.hls.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(ee.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(ee.DESTROYING,this.onDestroying,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(ee.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(ee.DESTROYING,this.onDestroying,this)}},{key:"getLicenseServerUrl",value:function(e){var t=this.config,r=t.drmSystems,i=t.widevineLicenseUrl,n=null==r?void 0:r[e];return n?n.licenseUrl:e===hi.WIDEVINE&&i?i:void 0}},{key:"getLicenseServerUrlOrThrow",value:function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'.concat(e,'"'));return t}},{key:"getServerCertificateUrl",value:function(e){var t=this.config.drmSystems,r=null==t?void 0:t[e];if(r)return r.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]'))}},{key:"attemptKeySystemAccess",value:function(e){var t=this,r=this.hls.levels,i=function(e,t,r){return!!e&&r.indexOf(e)===t},n=r.map(function(e){return e.audioCodec}).filter(i),a=r.map(function(e){return e.videoCodec}).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(r,i){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then(function(e){return r({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):i(t instanceof ko?t:new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}},{key:"requestMediaKeySystemAccess",value:function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function ".concat(r);return null===Ti&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(i))}return r(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,r){var i,n=this,a=function(e,t,r,i){var n;switch(e){case hi.FAIRPLAY:n=["cenc","sinf"];break;case hi.WIDEVINE:case hi.PLAYREADY:n=["cenc"];break;case hi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}}),videoCapabilities:r.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}})}]}(n,t,r,i)}(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(i=s)?void 0:i.keySystemAccess;if(!o){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(Kt(a))),o=this.requestMediaKeySystemAccess(e,a);var l=s=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(function(t){n.log('Failed to obtain access to key-system "'.concat(e,'": ').concat(t))}),o.then(function(t){n.log('Access for key-system "'.concat(t.keySystem,'" obtained'));var r=n.fetchServerCertificate(e);n.log('Create media-keys for "'.concat(e,'"'));var i=l.mediaKeys=t.createMediaKeys().then(function(t){return n.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,r.then(function(r){return r?n.setMediaKeysServerCertificate(t,e,r):t})});return i.catch(function(t){n.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),i})}return o.then(function(){return s.mediaKeys})}},{key:"createMediaKeySessionContext",value:function(e){var t=e.decryptdata,r=e.keySystem,i=e.mediaKeys;this.log('Creating key-system session "'.concat(r,'" keyId: ').concat(Ae(t.keyId||[])," keyUri: ").concat(t.uri));var n=i.createSession(),a={decryptdata:t,keySystem:r,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}},{key:"renewKeySession",value:function(e){var t=e.decryptdata;if(t.pssh){var r=this.createMediaKeySessionContext(e),i=yo(t);this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}},{key:"updateKeySession",value:function(e,t){var r=e.mediaKeysSession;return this.log('Updating key-session "'.concat(r.sessionId,'" for keyId ').concat(Ae(e.decryptdata.keyId||[]),"\n } (data length: ").concat(t.byteLength,")")),r.update(t)}},{key:"getSelectedKeySystemFormats",value:function(){var e=this;return Object.keys(this.keySystemAccessPromises).map(function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}}).filter(function(e){return!!e.hasMediaKeys}).map(function(e){return yi(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var r=e.keySystem,i=e.mediaKeys;return t.attemptSetMediaKeys(r,i)})}},{key:"selectKeySystem",value:function(e){var t=this;return new Promise(function(r,i){t.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,n=yi(t);n?r(n):i(new Error('Unable to find format for key-system "'.concat(t,'"')))}).catch(i)})}},{key:"selectKeySystemFormat",value:function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(e.sn," ").concat(e.type,": ").concat(e.level,") key formats ").concat(t.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}},{key:"getKeyFormatPromise",value:function(e){var t=Ei(this.config),r=e.map(mi).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(r)}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var i=Eo(e,t[r]);if(i)return i}}},{key:"loadKey",value:function(e){var t=this,r=e.keyInfo.decryptdata,i=yo(r),n=this.bannedKeyIds[i];if(n||"internal-error"===this.getKeyStatus(r)){var a=To(n||"internal-error",r);return this.handleError(a,e.frag),Promise.reject(a)}var s="(keyId: ".concat(i,' format: "').concat(r.keyFormat,'" method: ').concat(r.method," uri: ").concat(r.uri,")");this.log("Starting session for key ".concat(s));var o=this.keyIdToKeySessionPromise[i];if(!o){var l=this.getKeySystemForKeyPromise(r).then(function(i){var n=i.keySystem,a=i.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: ".concat(e.frag.sn," ").concat(e.frag.type,": ").concat(e.frag.level," using key ").concat(s)),t.attemptSetMediaKeys(n,a).then(function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:n,mediaKeys:a,decryptdata:r})})}).then(function(e){var i=r.pssh?r.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return l.catch(function(r){return t.handleError(r,e.frag)}),this.keyIdToKeySessionPromise[i]=l,l}return o.catch(function(i){if(i instanceof ko){var n=fe({},i.data);"internal-error"===t.getKeyStatus(r)&&(n.decryptdata=r);var a=new ko(n,i.message);t.handleError(a,e.frag)}}),o}},{key:"throwIfDestroyed",value:function(){if(!this.hls)throw new Error("invalid state")}},{key:"handleError",value:function(e,t){if(this.hls)if(e instanceof ko){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error("".concat(e.message).concat(r?" (".concat(Ae(r.keyId||[]),")"):"")),this.hls.trigger(ee.ERROR,e.data)}else this.error(e.message),this.hls.trigger(ee.ERROR,{type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}},{key:"getKeySystemForKeyPromise",value:function(e){var t=yo(e),r=this.keyIdToKeySessionPromise[t];if(!r){var i=mi(e.keyFormat),n=i?[i]:Ei(this.config);return this.attemptKeySystemAccess(n)}return r}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=Ei(this.config)),0===e.length)throw new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(Kt({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}},{key:"attemptSetMediaKeys",value:function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var n=Promise.all(i).then(function(){return r.media?r.media.setMediaKeys(t):new Promise(function(e,i){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return i(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(i)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(function(){r.log('Media-keys set for "'.concat(e,'"')),i.push(n),r.setMediaKeysQueue=r.setMediaKeysQueue.filter(function(e){return-1===i.indexOf(e)})})}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,r,i){var n,a=this,s=null==(n=this.config.drmSystems)||null==(n=n[e.keySystem])?void 0:n.generateRequest;if(s)try{var o=s.call(this.hls,t,r,e);if(!o)throw new Error("Invalid response from configured generateRequest filter");t=o.initDataType,r=o.initData?o.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===r)return this.log('Skipping key-session request for "'.concat(i,'" (no initData)')),Promise.resolve(e);var l=yo(e.decryptdata),u=e.decryptdata.uri;this.log('Generating key-session request for "'.concat(i,'" keyId: ').concat(l," URI: ").concat(u," (init data type: ").concat(t," length: ").concat(r.byteLength,")"));var c=new Pn,d=e._onmessage=function(t){var r=e.mediaKeysSession;if(r){var i=t.messageType,n=t.message;a.log('"'.concat(i,'" message event for session "').concat(r.sessionId,'" message size: ').concat(n.byteLength)),"license-request"===i||"license-renewal"===i?a.renewLicense(e,n).catch(function(e){c.eventNames().length?c.emit("error",e):a.handleError(e)}):"license-release"===i?e.keySystem===hi.FAIRPLAY&&a.updateKeySession(e,li("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(i,'"'))}else c.emit("error",new Error("invalid state"))},h=function(e,t){var r;t.keyStatus=e,e.startsWith("usable")?c.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=To(e,t.decryptdata):"expired"===e?r=new Error("key expired (keyId: ".concat(l,")")):"released"===e?r=new Error("key released"):"status-pending"===e||a.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(l,")")),r&&(c.eventNames().length?c.emit("error",r):a.handleError(r))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){var r=a.getKeyStatuses(e);if(Object.keys(r).some(function(e){return"status-pending"!==r[e]})){if("expired"===r[l])return a.log("Expired key ".concat(Kt(r),' in key-session "').concat(e.mediaKeysSession.sessionId,'"')),void a.renewKeySession(e);var i=r[l];if(i)h(i,e);else{var n;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(n=e.keyStatusTimeouts)[l]||(n[l]=self.setTimeout(function(){if(e.mediaKeysSession&&a.mediaKeys){var t=a.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return a.log("No status for keyId ".concat(l,' in key-session "').concat(e.mediaKeysSession.sessionId,'". Using session key-status ').concat(t," from other session.")),h(t,e);a.log("key status for ".concat(l,' in key-session "').concat(e.mediaKeysSession.sessionId,'" timed out after ').concat(1e3,"ms")),h(i="internal-error",e)}},1e3)),a.log("No status for keyId ".concat(l," (").concat(Kt(r),")."))}}}else c.emit("error",new Error("invalid state"))};ln(e.mediaKeysSession,"message",d),ln(e.mediaKeysSession,"keystatuseschange",f);var v=new Promise(function(e,t){c.on("error",t),c.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,r).then(function(){a.log('Request generated for key-session "'.concat(e.mediaKeysSession.sessionId,'" keyId: ').concat(l," URI: ").concat(u))}).catch(function(t){throw new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},"Error generating key-session request: ".concat(t))}).then(function(){return v}).catch(function(t){return c.removeAllListeners(),a.removeSession(e).then(function(){throw t})}).then(function(){return c.removeAllListeners(),e})}},{key:"getKeyStatuses",value:function(e){var t=this,r={};return e.mediaKeysSession.keyStatuses.forEach(function(i,n){if("string"==typeof n&&"object"===S(i)){var a=n;n=i,i=a}var s="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);e.keySystem===hi.PLAYREADY&&16===s.length&&ui(s);var o=Ae(s);"internal-error"===i&&(t.bannedKeyIds[o]=i),t.log('key status change "'.concat(i,'" for keyStatuses keyId: ').concat(o,' key-session "').concat(e.mediaKeysSession.sessionId,'"')),r[o]=i}),r}},{key:"fetchServerCertificate",value:function(e){var t=this.config,r=new(0,t.loader)(t),i=this.getServerCertificateUrl(e);return i?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(n,a){var s={responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,i){n(e.data)},onError:function(t,r,n,o){a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:fe({url:s.url,data:void 0},t)},'"'.concat(e,'" certificate request failed (').concat(i,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,r,n){a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:s.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(i,")")))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)})):Promise.resolve()}},{key:"setMediaKeysServerCertificate",value:function(e,t,r){var i=this;return new Promise(function(n,a){e.setServerCertificate(r).then(function(a){i.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(r.byteLength,') on "').concat(t,'"')),n(e)}).catch(function(e){a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}},{key:"renewLicense",value:function(e,t){var r=this;return this.requestLicense(e,new Uint8Array(t)).then(function(t){return r.updateKeySession(e,new Uint8Array(t)).catch(function(t){throw new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)})})}},{key:"unpackPlayReadyKeyMessage",value:function(e,t){var r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var i=(new DOMParser).parseFromString(r,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0)for(var a,s=0,o=n.length;s<o;s++){var l,u,c=null==(l=(a=n[s]).querySelector("name"))?void 0:l.textContent,d=null==(u=a.querySelector("value"))?void 0:u.textContent;c&&d&&e.setRequestHeader(c,d)}var h=i.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return li(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,r,i){var n=this,a=this.config.licenseXhrSetup;return a?Promise.resolve().then(function(){if(!r.decryptdata)throw new Error("Key removed");return a.call(n.hls,e,t,r,i)}).catch(function(s){if(!r.decryptdata)throw s;return e.open("POST",t,!0),a.call(n.hls,e,t,r,i)}).then(function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||i}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}},{key:"requestLicense",value:function(e,t){var r=this,i=this.config.keyLoadPolicy.default;return new Promise(function(n,a){var s=r.getLicenseServerUrlOrThrow(e.keySystem);r.log("Sending license request to URL: ".concat(s));var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!r.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===o.readyState)if(200===o.status){r._requestLicenseFailureCount=0;var l=o.response;r.log("License received ".concat(l instanceof ArrayBuffer?l.byteLength:l));var u=r.config.licenseResponseCallback;if(u)try{l=u.call(r.hls,o,s,e)}catch(e){r.error(e)}n(l)}else{var c=i.errorRetry,d=c?c.maxNumRetry:0;if(r._requestLicenseFailureCount++,r._requestLicenseFailureCount>d||o.status>=400&&o.status<500)a(new ko({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:s,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed (".concat(s,"). Status: ").concat(o.status," (").concat(o.statusText,")")));else{var h=d-r._requestLicenseFailureCount+1;r.warn("Retrying license request, ".concat(h," attempts left")),r.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,r.setupLicenseXHR(o,s,e,t).then(function(t){var i=t.xhr,n=t.licenseChallenge;e.keySystem==hi.PLAYREADY&&(n=r.unpackPlayReadyKeyMessage(i,n)),i.send(n)}).catch(a)})}},{key:"onDestroying",value:function(){this.unregisterListeners(),this._clear()}},{key:"onMediaAttached",value:function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,ln(r,"encrypted",this.onMediaEncrypted),ln(r,"waitingforkey",this.onWaitingForKey);var i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(un(e,"encrypted",this.onMediaEncrypted),un(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}},{key:"_clear",value:function(){var e,r=this;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};var i=this.mediaResolved;if(i&&i(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ai.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return r.removeSession(e)}).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch(function(e){r.log("Could not clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: ".concat(e))})}))||Promise.resolve())).catch(function(e){r.log("Could not close sessions and clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(e))})}).then(function(){s&&r.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear()}},{key:"onManifestLoaded",value:function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(i.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(i)}}},{key:"removeSession",value:function(e){var t=this,r=e.mediaKeysSession,i=e.licenseXhr,n=e.decryptdata;if(r){this.log('Remove licenses and keys and close session "'.concat(r.sessionId,'" keyId: ').concat(Ae((null==n?void 0:n.keyId)||[]))),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);var s=e.keyStatusTimeouts;s&&Object.keys(s).forEach(function(e){return self.clearTimeout(s[e])});var o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise(function(e,t){self.setTimeout(function(){return t(new Error("MediaKeySession.remove() timeout"))},8e3),r.remove().then(e).catch(t)}):Promise.resolve();return o.catch(function(e){t.log("Could not remove session: ".concat(e)),t.hls&&t.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(e))})}).then(function(){return r.close()}).catch(function(e){t.log("Could not close session: ".concat(e)),t.hls&&t.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(e))})})}return Promise.resolve()}}])}(ve);function yo(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Ae(e.keyId)}function Eo(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}mo.CDMCleanupPromise=void 0;var ko=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r])).data=void 0,e.error||(e.error=new Error(r)),i.data=e,e.err=e.error,i}return d(t,e),o(t)}(L(Error));function To(e,t){var r="output-restricted"===e,i=r?Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ko({type:J.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'.concat(e,'"'))}var So=function(){return o(function e(t){a(this,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=t,this.registerListeners()},[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"registerListeners",value:function(){this.hls.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"destroy",value:function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(ee.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(ee.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}])}();function bo(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Ao(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: ".concat(t))}catch(r){ke.debug("[texttrack-utils]: ".concat(r));try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){ke.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(e))}}"disabled"===r&&(e.mode=r)}function Lo(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(var i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===r&&(e.mode=r)}function Io(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;var i,n=0,a=r;for(;n<=a;)if(t<e[i=Math.floor((a+n)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}return e[n].startTime-t<t-e[a].startTime?n:a}(e,t);if(n>-1)for(var a=n,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;s<a.length;s++)i&&!i(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}function Ro(e){for(var t=[],r=0;r<e.length;r++){var i=e[r];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||t.push(e[r])}return t}var wo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e,"subtitle-track-controller"])).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){for(var e=null,t=Ro(r.media.textTracks),i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}var n=r.findTrackForTextTrack(e);r.subtitleTrack!==n&&r.setSubtitleTrack(n)}},r.registerListeners(),r}return d(t,e),o(t,[{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,E(t,"destroy",this,3)([])}},{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}},{key:"pollTrackChange",value:function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}},{key:"onMediaDetaching",value:function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!i)Ro(r.textTracks).forEach(function(e){Lo(e)})}}},{key:"onManifestLoading",value:function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.subtitleTracks}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.subtitleGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.subtitlePreference;if(!n&&s){this.selectDefaultTrack=!1;var o=qt(s,a);if(o>-1)n=a[o];else{var l=qt(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={subtitleTracks:a};this.log("Updating subtitle tracks, ".concat(a.length,' track(s) found in "').concat(null==r?void 0:r.join(","),'" group-id')),this.hls.trigger(ee.SUBTITLE_TRACKS_UPDATED,c),-1!==u&&-1===this.trackId&&this.setSubtitleTrack(u)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i<t.length;i++){var n=t[i];if((!r||n.default)&&(r||e)&&(!e||zt(n,e)))return i}if(e){for(var a=0;a<t.length;a++){var s=t[a];if(ls(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if(ls(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1}},{key:"findTrackForTextTrack",value:function(e){if(e)for(var t=this.tracksInGroup,r=0;r<t.length;r++){if(us(t[r],e))return r}return-1}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&(t.context.type!==ne||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}},{key:"setSubtitleOption",value:function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&zt(e,r))return r;var i=qt(e,this.tracksInGroup);if(i>-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}if(r)return null;var a=qt(e,t);if(a>-1)return t[a]}}return null}},{key:"loadPlaylist",value:function(e){E(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}},{key:"loadingPlaylist",value:function(e,r){E(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ee.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this.media;if(e){var t,r=Ro(e.textTracks),i=this.currentTrack;if(i&&((t=r.filter(function(e){return us(i,e)})[0])||this.warn('Unable to find subtitle TextTrack with name "'.concat(i.name,'" and language "').concat(i.lang,'"'))),[].slice.call(r).forEach(function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")}),t){var n=this.subtitleDisplay?"showing":"hidden";t.mode!==n&&(t.mode=n)}}}},{key:"setSubtitleTrack",value:function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!X(e))this.warn("Invalid subtitle track id: ".concat(e));else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),i){var n=!!i.details&&!i.details.live;if(e!==this.trackId||i!==r||!n){this.log("Switching to subtitle-track ".concat(e)+(i?' "'.concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId):""));var a=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,c=i.url;this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:c});var d=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(d)}}else this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e}}])}(ss);function Po(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var xo=.025,Do=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Co(e,t,r){return"".concat(e.identifier,"-").concat(r+1,"-").concat(Po(t))}var _o=function(){return o(function e(t,r){a(this,e),this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)},[{key:"setDateRange",value:function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}},{key:"reset",value:function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}},{key:"isAssetPastPlayoutLimit",value:function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)}},{key:"findAssetIndex",value:function(e){return this.assetList.indexOf(e)}},{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Mo(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-Mo(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=X(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Mo(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<xo))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Do.Range:Do.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}},{key:"toString",value:function(){return'["'.concat((e=this).identifier,'" ').concat(e.cue.pre?"<pre>":e.cue.post?"<post>":"").concat(e.timelineStart.toFixed(2),"-").concat(e.resumeTime.toFixed(2),"]");var e}}])}();function Mo(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<xo)?t.start:t.start+t.duration}function Oo(e,t,r){var i=new self.URL(e,r);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",t),i}function Fo(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function No(e){var t=e.timelineStart,r=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+r).toFixed(2),"]")}var Uo=function(){return o(function e(t,r,i,n){var s=this;a(this,e),this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){s.reachedPlayout(s.currentTime)&&s.hls&&s.hls.trigger(ee.PLAYOUT_LIMIT_REACHED,{})};var o=this.hls=new t(r);this.interstitial=i,this.assetItem=n;var l=function(){s.hasDetails=!0};o.once(ee.LEVEL_LOADED,l),o.once(ee.AUDIO_TRACK_LOADED,l),o.once(ee.SUBTITLE_TRACK_LOADED,l),o.on(ee.MEDIA_ATTACHING,function(e,t){var r=t.media;s.removeMediaListeners(),s.mediaAttached=r,s.interstitial.playoutLimit&&(r.addEventListener("timeupdate",s.checkPlayout),s.appendInPlace&&o.on(ee.BUFFER_APPENDED,function(){var e=s.bufferedEnd;s.reachedPlayout(e)&&(s._bufferedEosTime=e,o.trigger(ee.BUFFERED_TO_END,void 0))}))})},[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"loadSource",value:function(){var e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{var t=this.assetItem.uri;try{t=Oo(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}},{key:"bufferedInPlaceToEnd",value:function(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;var r=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,n=jr.bufferInfo(e,i,0);return this.getAssetTime(n.end)>=r-.02}},{key:"reachedPlayout",value:function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=jr.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r<e)return r}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}},{key:"getAssetTime",value:function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}},{key:"removeMediaListeners",value:function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}},{key:"bufferSnapShot",value:function(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}},{key:"destroy",value:function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}},{key:"attachMedia",value:function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}},{key:"detachMedia",value:function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.hls)||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.hls)||e.pauseBuffering()}},{key:"transferMedia",value:function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}},{key:"resetDetails",value:function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}},{key:"on",value:function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)}},{key:"once",value:function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)}},{key:"off",value:function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)}},{key:"toString",value:function(){var e;return"HlsAssetPlayer: ".concat(No(this.assetItem)," ").concat(null==(e=this.hls)?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}])}(),Bo=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["interstitials-sched",r])).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=e,i}return d(t,e),o(t,[{key:"destroy",value:function(){this.reset(),this.onScheduleUpdate=null}},{key:"reset",value:function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(function(e){return e.reset()}),this.events=this.items=null}},{key:"resetErrorsInRange",value:function(e,t){return this.events?this.events.reduce(function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r},0):0}},{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"getEvent",value:function(e){return e&&this.eventMap[e]||null}},{key:"hasEvent",value:function(e){return e in this.eventMap}},{key:"findItemIndex",value:function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r}},{key:"findItemIndexAtTime",value:function(e,t){var r=this.items;if(r)for(var i=0;i<r.length;i++){var n=r[i];if(t&&"primary"!==t&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return i}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var r=this.items;if(r)for(var i=e;i<=t&&r[i];i++){var n=r[i].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return i}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return-1}},{key:"findAssetIndex",value:function(e,t){var r=e.assetList,i=r.length;if(i>1)for(var n=0;n<i;n++){var a=r[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===i-1))return n}}return 0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var r=t.assetList,i=r[r.length-1];if(i)return i.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var r=this,i=e.main.details,n=i.dateRanges,a=this.events,s=this.parseDateRanges(n,{url:i.url},t),o=Object.keys(n),l=a?a.filter(function(e){return!o.includes(e.identifier)}):[];s.length&&s.sort(function(e,t){var r=e.cue.pre,i=e.cue.post,n=t.cue.pre,a=t.cue.post;if(r&&!n)return-1;if(n&&!r)return 1;if(i&&!a)return 1;if(a&&!i)return-1;if(!(r||n||i||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=s,l.forEach(function(e){r.removeEvent(e)}),this.updateSchedule(e,l)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=this.events||[];if(i.length||t.length||this.length<2){var n=this.items,a=this.parseSchedule(i,e);(r||t.length||(null==n?void 0:n.length)!==a.length||a.some(function(e,t){return Math.abs(e.playout.start-n[t].playout.start)>.005||Math.abs(e.playout.end-n[t].playout.end)>.005}))&&(this.items=a,this.onScheduleUpdate(t,n))}}},{key:"parseDateRanges",value:function(e,t,r){for(var i=[],n=Object.keys(e),a=0;a<n.length;a++){var s=n[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new _o(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),i.push(l)}}return i}},{key:"parseSchedule",value:function(e,t){var r=[],i=t.main.details,n=i.live?1/0:i.edge,a=0;if((e=e.filter(function(e){return!(e.error||e.cue.once&&e.hasPlayed)})).length){this.resolveOffsets(e,t);var s=0,o=0;if(e.forEach(function(t,i){var l=t.cue.pre,u=t.cue.post,c=e[i-1]||null,d=t.appendInPlace,h=u?n:t.startOffset,f=t.duration,v=t.timelineOccupancy===Do.Range?f:0,g=t.resumptionOffset,p=(null==c?void 0:c.startTime)===h,m=h+t.cumulativeDuration,y=d?m+f:h+g;if(l||!u&&h<=0){var E=o;o+=v,t.timelineStart=m;var k=a;a+=f,r.push({event:t,start:m,end:y,playout:{start:k,end:a},integrated:{start:E,end:o}})}else{if(!(h<=n))return;if(!p){var T=h-s;if(T>.033){var S=s,b=o;o+=T;var A=a;a+=T;var L={previousEvent:e[i-1]||null,nextEvent:t,start:S,end:S+T,playout:{start:A,end:a},integrated:{start:b,end:o}};r.push(L)}else T>0&&c&&(c.cumulativeDuration+=T,r[r.length-1].end=h)}u&&(y=m),t.timelineStart=m;var I=o;o+=v;var R=a;a+=f,r.push({event:t,start:m,end:y,playout:{start:R,end:a},integrated:{start:I,end:o}})}var w=t.resumeTime;s=u||w>n?n:w}),s<n){var l,u=s,c=o,d=n-s;o+=d;var h=a;a+=d,r.push({previousEvent:(null==(l=r[r.length-1])?void 0:l.event)||null,nextEvent:null,start:s,end:u+d,playout:{start:h,end:a},integrated:{start:c,end:o}})}this.setDurations(n,a,o)}else{r.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n)}return r}},{key:"setDurations",value:function(e,t,r){this.durations={primary:e,playout:t,integrated:r}}},{key:"resolveOffsets",value:function(e,t){var r=this,i=t.main.details,n=i.live?1/0:i.edge,a=0,s=-1;e.forEach(function(o,l){var u=o.cue.pre,c=o.cue.post,d=u?0:c?n:o.startTime;(r.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=er(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(r.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1));!o.appendInPlace&&l+1<e.length&&(e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event ".concat(o))));var h=X(o.resumeOffset)?o.resumeOffset:o.duration;a+=h})}},{key:"primaryCanResumeInPlaceAt",value:function(e,t){var r=this,i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>xo?(this.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with estimated timeline end ").concat(n)),!1):!Object.keys(t).some(function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," past ").concat(n," playlist end ").concat(s)),!1;var o=er(null,a.fragments,i);if(!o)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," does not align with any fragments in ").concat(n," playlist (").concat(a.fragStart,"-").concat(a.fragmentEnd,")")),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)<xo+l||Math.abs(o.end-i)<xo+l)&&(r.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with ").concat(n," fragment bounds (").concat(o.start,"-").concat(o.end," sn: ").concat(o.sn," cc: ").concat(o.cc,")")),!0)})}},{key:"updateAssetDurations",value:function(e){if(e.assetListLoaded){for(var t=e.timelineStart,r=0,i=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,i||(i=null===s.duration),n||(n=!!s.error),r+=s.error?0:s.duration||0}e.duration=i&&!n?Math.max(r,e.duration):r}}},{key:"removeEvent",value:function(e){e.reset(),delete this.eventMap[e.identifier]}}])}(ve);function Go(e){return"[".concat(e.event?'"'+e.event.identifier+'"':"primary",": ").concat(e.start.toFixed(2),"-").concat(e.end.toFixed(2),"]")}var Ho=function(){return o(function e(t){a(this,e),this.hls=void 0,this.hls=t},[{key:"destroy",value:function(){this.hls=null}},{key:"loadAssetList",value:function(e,t){var r,i=this,n=e.assetListUrl;try{r=Oo(n,this.hls.sessionId,e.baseUrl)}catch(t){var a=this.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(ee.ERROR,a)}t&&"data:"!==r.protocol&&r.searchParams.set("_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,r,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,i.hls.trigger(ee.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=i.assignAssetListError(e,Z.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,a);i.hls.trigger(ee.ERROR,l)}},onError:function(t,r,n,a){var s=i.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(r.url,")")),r.url,a,n);i.hls.trigger(ee.ERROR,s)},onTimeout:function(t,r,n){var a=i.assignAssetListError(e,Z.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(r.url,")")),r.url,t,n);i.hls.trigger(ee.ERROR,a)}};return o.load(l,c,d),this.hls.trigger(ee.ASSET_LIST_LOADING,{event:e}),o}},{key:"assignAssetListError",value:function(e,t,r,i,n,a){return e.error=r,{type:J.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:r,networkDetails:a,stats:n}}}])}();function Vo(e){var t;null==e||null==(t=e.play())||t.catch(function(){})}function Ko(e,t){return"[".concat(e,"] Advancing timeline position to ").concat(t)}var jo=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,i.hls=void 0,i.assetListLoader=void 0,i.mediaSelection=null,i.altSelection=null,i.media=null,i.detachedData=null,i.requiredTracks=null,i.manager=null,i.playerQueue=[],i.bufferedPos=-1,i.timelinePos=-1,i.schedule=void 0,i.playingItem=null,i.bufferingItem=null,i.waitingItem=null,i.endedItem=null,i.playingAsset=null,i.endedAsset=null,i.bufferingAsset=null,i.shouldPlay=!1,i.onPlay=function(){i.shouldPlay=!0},i.onPause=function(){i.shouldPlay=!1},i.onSeeking=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&i.schedule){var t=e-i.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;i.timelinePos=e,i.bufferedPos=e;var n=i.playingItem;if(n){if(r)i.schedule.resetErrorsInRange(e,e-t)&&i.updateSchedule(!0);if(i.checkBuffer(),r&&e<n.start||e>=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked ".concat(r?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(r&&e<d||e>=d+h)null!=(c=n.event)&&c.appendInPlace&&(i.clearInterstitial(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u)}else if(i.playingLastItem&&i.isInterstitial(n)){var f=n.event.assetList[0];f&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,f))}}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&e>i.timelinePos){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;if(n)e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return Go(e)})," pos: ").concat(i.timelinePos)),l.length&&i.log("Removed events ".concat(l));var c=null,d=null;n&&(c=i.updateItem(n,i.timelinePos),i.itemsMatch(n,c)?i.playingItem=c:i.waitingItem=i.endedItem=null),i.waitingItem=i.updateItem(i.waitingItem),i.endedItem=i.updateItem(i.endedItem);var h=i.bufferingItem;if(h&&(d=i.updateItem(h,i.bufferedPos),i.itemsMatch(h,d)?i.bufferingItem=d:h.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){i.clearAssetPlayer(e.identifier,null)})}),i.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>xo&&i.warn("".concat(n,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(i.hls.trigger(ee.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.includes(n.event.identifier))return i.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),void i.primaryFallback(n.event);n&&i.trimInPlace(c,n),h&&d!==c&&i.trimInPlace(d,h),i.checkBuffer()}}},i.hls=e,i.HlsPlayerClass=r,i.assetListLoader=new Ho(e),i.schedule=new Bo(i.onScheduleUpdate,e.logger),i.registerListeners(),i}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(ee.MEDIA_ENDED,this.onMediaEnded,this),e.on(ee.ERROR,this.onError,this),e.on(ee.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(ee.MEDIA_ENDED,this.onMediaEnded,this),e.off(ee.ERROR,this.onError,this),e.off(ee.DESTROYING,this.onDestroying,this))}},{key:"startLoad",value:function(){this.resumeBuffering()}},{key:"stopLoad",value:function(){this.pauseBuffering()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}},{key:"onDestroying",value:function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}},{key:"removeMediaListeners",value:function(e){un(e,"play",this.onPlay),un(e,"pause",this.onPause),un(e,"seeking",this.onSeeking),un(e,"timeupdate",this.onTimeupdate)}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;ln(r,"seeking",this.onSeeking),ln(r,"timeupdate",this.onTimeupdate),ln(r,"play",this.onPlay),ln(r,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}}},{key:"clearScheduleState",value:function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and ".concat(n)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}},{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==Do.Point){var c=r(a);(null==c?void 0:c.interstitial)===u&&(l+=c.assetItem.startOffset+c[o])}}else l+=("bufferedPos"===s?n():e[s])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,i;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},s=function(t,n){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to ".concat(t,' "').concat(n,'"'));var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,n),c=null==(s=e.schedule.items)?void 0:s[u],d=e.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,v=l&&e.itemsMatch(l,c);if(l&&(f||v)){var g=r(e.playingAsset),p=(null==g?void 0:g.media)||e.primaryMedia;if(p){var m="primary"===n?p.currentTime:i(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-m,E=(f?m:p.currentTime)+y;if(E>=0&&(!g||f||E<=g.duration))return void(p.currentTime=E)}}if(c){var k=t;if("primary"!==n){var T=t-c[n].start;k=c.start+T}var S=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!S&&!c.event.appendInPlace){if(l){var b=e.findItemIndex(l);if(u>b){var A=e.schedule.findJumpRestrictedIndex(b+1,u);if(A>b)return void e.setSchedulePosition(A)}var L=0;if(S)e.timelinePos=k,e.checkBuffer();else for(var I=c.event.assetList,R=t-(c[n]||c).start,w=I.length;w--;){var P=I[w];if(P.duration&&R>=P.startOffset&&R<P.startOffset+P.duration){L=w;break}}e.setSchedulePosition(u,L)}}else{var x=e.media||(f?null==d?void 0:d.media:null);x&&(x.currentTime=k)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){var r,n=t(),a=e.bufferingItem;return a&&a===n&&(i(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(r=e.bufferingAsset)?void 0:r.startOffset))||0},get currentTime(){var t=o(),r=e.effectivePlayingItem;return r&&r===t?i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),i=e.effectivePlayingItem;i&&i===r&&s(t+i.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,r=null==(t=o())?void 0:t.event.assetList;return r?r.map(function(t){return e.getAssetPlayer(t.identifier)}):[]},get playingIndex(){var t,r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){var t;return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&X(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"isInterstitial",value:function(e){return!(null==e||!e.event)}},{key:"retreiveMediaSource",value:function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(Kt(n))),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}},{key:"transferMediaTo",value:function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else if(c){var d=this.getBufferingPlayer();d?(s=d.transferMedia(),a="".concat(d)):a="detached MediaSource"}else a="detached media";if(!s)if(c)s=this.detachedData,this.log("using detachedData: MediaSource ".concat(Kt(s)));else if(!this.detachedData||o.media===t){var h=this.playerQueue;h.length>1&&h.forEach(function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets ".concat(t))}}),this.hls.detachMedia(),this.detachedData={media:t}}var f=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState),v=f&&s?s:t;this.log("".concat(f?"transfering MediaSource":"attaching media"," to ").concat(l?e:"Primary"," from ").concat(a," (media.currentTime: ").concat(t.currentTime,")"));var g=this.schedule;if(v===s&&g){var p=l&&e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:!l||p,cueRemoval:!l}}e.attachMedia(v)}}},{key:"onInterstitialCueEnter",value:function(){this.onTimeupdate()}},{key:"checkStart",value:function(){var e=this.schedule,t=null==e?void 0:e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var r=this.timelinePos,i=this.effectivePlayingItem;if(-1===r){var n=this.hls.startPosition;if(this.log(Ko("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){var a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){var s=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(s);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){var l=e.findItemIndex(i);this.setSchedulePosition(l)}}}},{key:"advanceAssetBuffering",value:function(e,t){var r=e.event,i=r.findAssetIndex(t),n=Fo(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(e)+1];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(e,n)}},{key:"advanceAfterAssetEnded",value:function(e,t,r){var i=Fo(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=t+1;if(a>=n.length)return void this.setSchedulePosition(-1);var s=e.resumeTime;this.timelinePos<s&&(this.log(Ko("advanceAfterAssetEnded",s)),this.timelinePos=s,e.appendInPlace&&this.advanceInPlace(s),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){var o=e.assetList[i];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(t,i)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var r=this.schedule;if(r){var i=t.parentIdentifier,n=r.getEvent(i);if(n){var a=r.findEventIndex(i),s=r.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;if(i&&!this.playbackDisabled){var n=e>=0?i[e]:null;this.log("setSchedulePosition ".concat(e,", ").concat(t," (").concat(n?Go(n):n,") pos: ").concat(this.timelinePos));var a=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(a)){var o=a.event,l=this.playingAsset,u=null==l?void 0:l.identifier,c=u?this.getAssetPlayer(u):null;if(c&&u&&(!this.eventItemsMatch(a,n)||void 0!==t&&u!==o.assetList[t].identifier)){var d,h=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED ".concat(h+1,"/").concat(o.assetList.length," ").concat(No(l))),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(ee.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:h,event:o,schedule:i.slice(0),scheduleIndex:e,player:c}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),h));this.retreiveMediaSource(u,n),!c.media||null!=(d=this.detachedData)&&d.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log("INTERSTITIAL_ENDED ".concat(o," ").concat(Go(a))),o.hasPlayed=!0,this.hls.trigger(ee.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once)){var f;this.updateSchedule();var v=null==(f=this.schedule)?void 0:f.items;if(n&&v){var g=this.findItemIndex(n);this.advanceSchedule(g,v,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(i<e||i>e+1)&&a.clearInterstitial(r,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===r){var d=Fo(c,(r=s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,r);r=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,r);if(this.eventItemsMatch(o,h||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED ".concat(Go(o)," ").concat(c.appendInPlace?"append in place":"")),this.hls.trigger(ee.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading ".concat(c));if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial ".concat(c));this.waitingItem=this.endedItem=null,this.playingItem=o;var v=c.assetList[r];if(!v)return void this.advanceAfterAssetEnded(c,e,r||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(r+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,r,t,e,l),this.shouldPlay&&Vo(f.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Vo(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"resumePrimary",value:function(e,t,r){var i,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming ".concat(Go(e))),null==(i=this.detachedData)||!i.mediaSource){var a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Ko("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(r){var s=null==(n=this.schedule)?void 0:n.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(Go(e))),this.hls.trigger(ee.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}}},{key:"getPrimaryResumption",value:function(e,t){var r=e.start;if(this.primaryLive){var i=this.primaryDetails;if(0===t)return this.hls.startPosition;if(i&&(r<i.fragmentStart||r>i.edge))return this.hls.liveSyncPosition||-1}return r}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:jr.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Ko("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var r,i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(r=i.mainForwardBufferInfo)?void 0:r.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}},{key:"onManifestLoading",value:function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ee.BUFFER_CODECS,this.onBufferCodecs,this)}},{key:"onLevelUpdated",value:function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=fe(fe({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var r=this.hls.audioTracks[t.id],i=this.mediaSelection;if(i){var n=fe(fe({},i),{},{audio:r});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{audio:r})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var r=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(i){var n=fe(fe({},i),{},{subtitles:r});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{subtitles:r})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=Wt(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setAudioOption(t)||i.setAudioOption(r))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r=Wt(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setSubtitleOption(t)||-1!==t.id&&i.setSubtitleOption(r))})}},{key:"onBufferCodecs",value:function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var r=0;r<t.length;r++){var i=t[r];if(i.cue.post){var n,a=this.schedule.findEventIndex(i.identifier),s=null==(n=this.schedule.items)?void 0:n[a];this.isInterstitial(s)&&this.eventItemsMatch(s,this.bufferingItem)&&this.bufferedToItem(s,0);break}}this.bufferedPos=Number.MAX_VALUE}}}},{key:"onMediaEnded",value:function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;return e&&i&&i[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var r=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)});var i=e.end+.25,n=jr.bufferInfo(this.primaryMedia,i,0);if(n.end>i||(n.nextStart||0)>i){this.log("trim buffered interstitial ".concat(Go(e)," (was ").concat(Go(t),")"));this.attachPrimary(i,null,!0),this.flushFrontBuffer(i)}}}},{key:"itemsMatch",value:function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}},{key:"eventItemsMatch",value:function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}},{key:"findItemIndex",value:function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}},{key:"updateSchedule",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=this.mediaSelection;r&&(null==(e=this.schedule)||e.updateSchedule(r,[],t))}},{key:"checkBuffer",value:function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=jr.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}}},{key:"updateBufferedPos",value:function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),d=t[c];if((-1===o&&n&&e>=n.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=c),this.isInterstitial(n)){var h=n.event;if(c-s>1&&!1===h.appendInPlace)return;if(0===h.assetList.length&&h.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else r&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var r=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var i=r.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,r=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,r)&&i){var n=i.items,a=i.events;if(!n||!a)return r;var s=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(Go(e))+(r?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,r){var i=t.getAssetPlayer(e.identifier);i&&(r===u&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(function(e){return e.pauseBuffering()});this.hls.trigger(ee.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;var i=this.detachedData;if(i)if(i.mediaSource){this.attachPrimary(e.start,e,!0)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}},{key:"preloadPrimary",value:function(e){var t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}},{key:"bufferedToEvent",value:function(e,t){var r=e.event,i=0===r.assetList.length&&!r.assetListLoader,n=r.cue.once;if(i||!n){var a=this.preloadAssets(r,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var r=e.assetUrl,i=e.assetList.length,n=0===i&&!e.assetListLoader,a=e.cue.once;if(n){var s,o=e.timelineStart;if(e.appendInPlace){var l,u=this.playingItem;this.isInterstitial(u)||(null==u||null==(l=u.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var c=0;if(!this.playingItem&&this.primaryLive&&-1===(c=this.hls.startPosition)&&(c=this.hls.liveSyncPosition||0),c&&!e.cue.pre&&!e.cue.post){var d=c-o;d>0&&(s=Math.round(1e3*d)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(r?1:i," ").concat(e).concat(s?" live-start: ".concat(c," start-offset: ").concat(s):"")),r)return this.createAsset(e,0,0,o,e.duration,r);var h=this.assetListLoader.loadAssetList(e,s);h&&(e.assetListLoader=h)}else if(!a&&i){for(var f=t;f<i;f++){var v=e.assetList[f],g=this.getAssetPlayerQueueIndex(v.identifier);-1!==g&&!this.playerQueue[g].destroyed||v.error||this.createAssetPlayer(e,v,f)}var p=e.assetList[t];if(p){var m=this.getAssetPlayer(p.identifier);return m&&m.loadSource(),m}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,r=this.requiredTracks;r&&(this.log("Removing front buffer starting at ".concat(e)),Object.keys(r).forEach(function(r){t.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})}))}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}},{key:"getAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}},{key:"getBufferingPlayer",value:function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}},{key:"createAsset",value:function(e,t,r,i,n,a){var s={parentIdentifier:e.identifier,identifier:Co(e,a,t),duration:n,startOffset:r,timelineStart:i,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,r){var i=this,n=this.hls,a=n.userConfig,s=a.videoPreference,o=n.loadLevelObj||n.levels[n.currentLevel];(s||o)&&(s=de({},s),o.videoCodec&&(s.videoCodec=o.videoCodec),o.videoRange&&(s.allowedVideoRanges=[o.videoRange]));var l=n.audioTracks[n.audioTrack],u=n.subtitleTracks[n.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){var d=this.timelinePos-t.timelineStart;if(d>1){var h=t.duration;h&&d<h&&(c=d)}}var f=t.identifier,v=fe(fe({},a),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:f,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:l||a.audioPreference,subtitlePreference:u||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var g=v.cmcd;null!=g&&g.sessionId&&g.contentId&&(v.cmcd=de({},g,{contentId:Po(t.uri)})),this.getAssetPlayer(f)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(f));var p=new Uo(this.HlsPlayerClass,v,e,t);this.playerQueue.push(p),e.assetList[r]=t;var m=!0,y=function(n){if(n.live){var a,s=new Error("Interstitials MUST be VOD assets ".concat(e)),o={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:s},l=(null==(a=i.schedule)?void 0:a.findEventIndex(e.identifier))||-1;i.handleAssetItemError(o,e,l,r,s.message)}else{var u=n.edge-n.fragmentStart,c=t.duration;(m||null===c||u>c)&&(m=!1,i.log('Interstitial asset "'.concat(f,'" duration change ').concat(c," > ").concat(u)),t.duration=u,i.updateSchedule())}};p.on(ee.LEVEL_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(ee.LEVEL_PTS_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(ee.EVENT_CUE_ENTER,function(){return i.onInterstitialCueEnter()});var E=function(e,t){var r=i.getAssetPlayer(f);if(r&&t.tracks){r.off(ee.BUFFER_CODECS,E),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};p.on(ee.BUFFER_CODECS,E);p.on(ee.BUFFERED_TO_END,function(){var r,n=i.getAssetPlayer(f);if(i.log("buffered to end of asset ".concat(n)),n&&i.schedule){var a=i.schedule.findEventIndex(e.identifier),s=null==(r=i.schedule.items)?void 0:r[a];i.isInterstitial(s)&&i.advanceAssetBuffering(s,t)}});var k=function(t){return function(){if(i.getAssetPlayer(f)&&i.schedule){i.shouldPlay=!0;var r=i.schedule.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return p.once(ee.MEDIA_ENDED,k(r)),p.once(ee.PLAYOUT_LIMIT_REACHED,k(1/0)),p.on(ee.ERROR,function(t,n){if(i.schedule){var a=i.getAssetPlayer(f);if(n.details===Z.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,"Asset player error ".concat(n.error," ").concat(e))}}),p.on(ee.DESTROYING,function(){if(i.getAssetPlayer(f)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly ".concat(f)),n={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(No(t))),this.hls.trigger(ee.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p}},{key:"clearInterstitial",value:function(e,t){var r=this;e.assetList.forEach(function(e){r.clearAssetPlayer(e.identifier,t)}),e.reset()}},{key:"resetAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'.concat(e,'" after error'));var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear ".concat(i," toSegment: ").concat(t?Go(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,u&&u.identifier===o||(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(No(s))),this.hls.trigger(ee.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)}},{key:"bufferAssetPlayer",value:function(e,t){var r,i;if(this.schedule){var n=e.interstitial,a=e.assetItem,s=this.schedule.findEventIndex(n.identifier),o=null==(r=this.schedule.items)?void 0:r[s];if(o){e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=a;var l=this.getBufferingPlayer();if(l!==e){var u=n.appendInPlace;if(!u||!1!==(null==l?void 0:l.interstitial.appendInPlace)){var c=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering ".concat(e));if(c&&!Se(c,e.tracks)){var d=new Error("Asset ".concat(No(a)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(c),"')")),h={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=n.findAssetIndex(a);return void this.handleAssetItemError(h,n,s,f,d.message)}}this.transferMediaTo(e,t)}}}}}},{key:"handleInPlaceStall",value:function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at ".concat(o," of ").concat(o+l," in ").concat(s," ").concat(e," (media.currentTime: ").concat(i,")")),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}}},{key:"advanceInPlace",value:function(e){var t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}},{key:"handleAssetItemError",value:function(e,t,r,i,n){if(e.details!==Z.BUFFER_STALLED_ERROR){var a=t.assetList[i]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?No(a):a," ").concat(e.error)),this.schedule){var s=(null==a?void 0:a.identifier)||"",o=this.getAssetPlayerQueueIndex(s),l=this.playerQueue[o]||null,u=this.schedule.items,c=de({},e,{fatal:!1,errorAction:Tr(!0),asset:a,assetListIndex:i,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(ee.INTERSTITIAL_ASSET_ERROR,c),e.fatal){var d=this.playingAsset,h=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(s,null),a.error=f),t.assetList.some(function(e){return!e.error}))for(var v=i;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===s?this.advanceAfterAssetEnded(t,r,i):h&&h.identifier===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,r=this.effectivePlayingItem;if(r){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(this.timelinePos," playing: ").concat(Go(r)," error: ").concat(e.error));var i=this.timelinePos;-1===i&&(i=this.hls.startPosition);var n=this.updateItem(r,i);if(this.itemsMatch(r,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;var a=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(a)}else this.checkStart()}},{key:"onAssetListLoaded",value:function(e,t){var r,i,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(r=this.schedule)&&r.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var r=parseFloat(e.DURATION);n.createAsset(a,t,c,l+c,r,e.URI),c+=r}),a.duration=c,this.log("Loaded asset-list with duration: ".concat(c," (was: ").concat(u,") ").concat(a));var d=this.waitingItem,h=(null==d?void 0:d.event.identifier)===s;this.updateSchedule();var f=null==(i=this.bufferingItem)?void 0:i.event;if(h){var v,g=this.schedule.findEventIndex(s),p=null==(v=this.schedule.items)?void 0:v[g];if(p){if(!this.playingItem&&this.timelinePos>p.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return a.error=new Error("Interstitial no longer within playback range ".concat(this.timelinePos," ").concat(a)),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(p)}this.setSchedulePosition(g)}else if((null==f?void 0:f.identifier)===s){var m=a.assetList[0];if(m){var y=this.getAssetPlayer(m.identifier);if(f.appendInPlace){var E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}}},{key:"onError",value:function(e,t){if(this.schedule)switch(t.details){case Z.ASSET_LIST_PARSING_ERROR:case Z.ASSET_LIST_LOAD_ERROR:case Z.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case Z.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);this.log("Primary player stall @".concat(this.timelinePos," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(ve),Yo=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"subtitle-stream-controller",oe])).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s.registerListeners(),s}return d(t,e),o(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),E(t,"onHandlerDestroying",this,3)([]),this.mainDetails=null}},{key:"registerListeners",value:function(){E(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"unregisterListeners",value:function(){E(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"startLoad",value:function(e,t){this.stopLoad(),this.state=hn,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"onManifestLoading",value:function(){E(t,"onManifestLoading",this,3)([]),this.mainDetails=null}},{key:"onMediaDetaching",value:function(e,r){this.tracksBuffered=[],E(t,"onMediaDetaching",this,3)([e,r])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var r=t.frag,i=t.success;if(this.fragContextChanged(r)||(Oe(r)&&(this.fragPrevious=r),this.state=hn),i){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=r.start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(function(e){for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}}),this.fragmentTracker.removeFragmentsInRange(r,n,oe)}}},{key:"onError",value:function(e,t){var r=t.frag;(null==r?void 0:r.type)===oe&&(t.details===Z.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dn&&(this.state=hn))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks;this.levels&&os(this.levels,i)?this.levels=i.map(function(e){return new Gt(e)}):(this.tracksBuffered=[],this.levels=i.map(function(e){var t=new Gt(e);return r.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,oe),this.fragPrevious=null,this.mediaBuffer=null)}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r;if(this.currentTrackId=t.id,null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==dn&&this.setInterval(500)}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r,i=this.currentTrackId,n=this.levels,a=t.details,s=t.id;if(n){var o=n[s];if(!(s>=n.length)&&o){this.log("Subtitle track ".concat(s," loaded [").concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;var u=this.mainDetails;if(!u)return void(this.startFragRequested=!1);var c,d=u.fragments[0];if(o.details)0===(l=this.alignPlaylists(a,o.details,null==(c=this.levelLastLoaded)?void 0:c.details))&&d&&zi(a,l=d.start);else a.hasProgramDateTime&&u.hasProgramDateTime?(on(a,u),l=a.fragmentStart):d&&zi(a,l=d.start);u&&!this.startFragRequested&&this.setStartPosition(u,l)}if(o.details=a,this.levelLastLoaded=o,s===i)if(this.hls.trigger(ee.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===hn)er(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}else this.warn("Subtitle tracks were reset while loading level ".concat(s))}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this,r=e.frag,i=e.payload,n=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&i&&i.byteLength>0&&null!=n&&n.key&&n.iv&&ai(n.method)){var s=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,si(n.method)).catch(function(e){throw a.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e}).then(function(e){var t=performance.now();a.trigger(ee.FRAG_DECRYPTED,{frag:r,payload:e,stats:{tstart:s,tdecrypt:t}})}).catch(function(e){t.warn("".concat(e.name,": ").concat(e.message)),t.state=hn})}}},{key:"doTick",value:function(){if(this.media){if(this.state===hn){var e=this.currentTrackId,t=this.levels,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;if(this.waitForLive(r))return;var i=this.config,n=this.getLoadPosition(),a=jr.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),s=a.end,o=a.len,l=r.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var u=l.fragments,c=u.length,d=l.edge,h=null,f=this.fragPrevious;if(s<d){var v=i.maxFragLookUpTolerance,g=s>d-v?0:v;!(h=er(f,u,Math.max(u[0].start,s),g))&&f&&f.start<u[0].start&&(h=u[0])}else h=u[c-1];if(!(h=this.filterReplacedPrimary(h,r.details)))return;var p=u[h.sn-l.startSN-1];if(p&&p.cc===h.cc&&this.fragmentTracker.getState(p)===Sr&&(h=p),this.fragmentTracker.getState(h)===Sr){var m=this.mapToInitFragWhenRequired(h);m&&this.loadFragment(m,r,s)}}}else this.state=hn}},{key:"loadFragment",value:function(e,r,i){Oe(e)?E(t,"loadFragment",this,3)([e,r,i]):this._loadInitSegment(e,r)}},{key:"mediaBufferTimeRanges",get:function(){return new Wo(this.tracksBuffered[this.currentTrackId]||[])}}])}(bn),Wo=o(function e(t){a(this,e),this.buffered=void 0;var r=function(e,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(r,") is greater than the maximum bound (").concat(i,")"));return t[r][e]};this.buffered={get length(){return t.length},end:function(e){return r("end",e,t.length)},start:function(e){return r("start",e,t.length)}}}),qo={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},zo=function(e){return String.fromCharCode(qo[e]||e)},Xo=15,Qo=100,$o={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Jo={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Zo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},el={25:2,26:4,29:6,30:8,31:10,27:13,28:15},tl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],rl=function(){return o(function e(){a(this,e),this.time=null,this.verboseLevel=0},[{key:"log",value:function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;ke.log("".concat(this.time," [").concat(e,"] ").concat(r))}}}])}(),il=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},nl=function(){return o(function e(){a(this,e),this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},[{key:"reset",value:function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}},{key:"setStyles",value:function(e){for(var t=["foreground","underline","italics","background","flash"],r=0;r<t.length;r++){var i=t[r];e.hasOwnProperty(i)&&(this[i]=e[i])}}},{key:"isDefault",value:function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}},{key:"equals",value:function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}},{key:"copy",value:function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}])}(),al=function(){return o(function e(){a(this,e),this.uchar=" ",this.penState=new nl},[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.copy(t)}},{key:"setPenState",value:function(e){this.penState.copy(e)}},{key:"equals",value:function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.copy(e.penState)}},{key:"isEmpty",value:function(){return" "===this.uchar&&this.penState.isDefault()}}])}(),sl=function(){return o(function e(t){a(this,e),this.chars=[],this.pos=0,this.currPenState=new nl,this.cueStartTime=null,this.logger=void 0;for(var r=0;r<Qo;r++)this.chars.push(new al);this.logger=t},[{key:"equals",value:function(e){for(var t=0;t<Qo;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}},{key:"copy",value:function(e){for(var t=0;t<Qo;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Qo;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}},{key:"setCursor",value:function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Qo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Qo)}},{key:"moveCursor",value:function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){var t=this;e>=144&&this.backSpace();var r=zo(e);this.pos>=Qo?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))}},{key:"clearFromPos",value:function(e){var t;for(t=e;t<Qo;t++)this.chars[t].reset()}},{key:"clear",value:function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{key:"clearToEndOfRow",value:function(){this.clearFromPos(this.pos)}},{key:"getTextString",value:function(){for(var e=[],t=!0,r=0;r<Qo;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}])}(),ol=function(){return o(function e(t){a(this,e),this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var r=0;r<Xo;r++)this.rows.push(new sl(t));this.logger=t},[{key:"reset",value:function(){for(var e=0;e<Xo;e++)this.rows[e].clear();this.currRow=14}},{key:"equals",value:function(e){for(var t=!0,r=0;r<Xo;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<Xo;t++)this.rows[t].copy(e.rows[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Xo;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}},{key:"backSpace",value:function(){this.rows[this.currRow].backSpace()}},{key:"clearToEndOfRow",value:function(){this.rows[this.currRow].clearToEndOfRow()}},{key:"insertChar",value:function(e){this.rows[this.currRow].insertChar(e)}},{key:"setPen",value:function(e){this.rows[this.currRow].setPenStyles(e)}},{key:"moveCursor",value:function(e){this.rows[this.currRow].moveCursor(e)}},{key:"setCursor",value:function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}},{key:"setPAC",value:function(e){this.logger.log(2,function(){return"pacData = "+Kt(e)});var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<Xo;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[i].cueStartTime,s=this.logger.time;if(null!==a&&null!==s&&a<s)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[i+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);l.setCursor(e.indent),e.color=l.chars[c].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)}},{key:"setBkgData",value:function(e){this.logger.log(2,function(){return"bkgData = "+Kt(e)}),this.backSpace(),this.setPen(e),this.insertChar(32)}},{key:"setRollUpRows",value:function(e){this.nrRollUpRows=e}},{key:"rollUp",value:function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,function(){return e.getDisplayText()});var t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")}},{key:"getDisplayText",value:function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<Xo;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),ll=function(){return o(function e(t,r,i){a(this,e),this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new ol(i),this.nonDisplayedMemory=new ol(i),this.lastOutputScreen=new ol(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i},[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,function(){return"MODE="+e}),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=this,r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);var i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return i+": "+t.writeScreen.getDisplayText(!0)}),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)}),this.outputDataUpdate())}},{key:"ccRCL",value:function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{key:"ccBS",value:function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{key:"ccAOF",value:function(){}},{key:"ccAON",value:function(){}},{key:"ccDER",value:function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{key:"ccRU",value:function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}},{key:"ccFON",value:function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}},{key:"ccRDC",value:function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{key:"ccTR",value:function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}},{key:"ccRTD",value:function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}},{key:"ccEDM",value:function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}},{key:"ccCR",value:function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}},{key:"ccENM",value:function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{key:"ccEOC",value:function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,function(){return"DISP: "+e.displayedMemory.getDisplayText()})}this.outputDataUpdate(!0)}},{key:"ccTO",value:function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}},{key:"ccMIDROW",value:function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+Kt(t)),this.writeScreen.setPen(t)}},{key:"outputDataUpdate",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}},{key:"cueSplitAtTime",value:function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}])}(),ul=function(){return o(function e(t,r,i){a(this,e),this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var n=this.logger=new rl;this.channels=[null,new ll(t,r,n),new ll(t+1,i,n)]},[{key:"getHandler",value:function(e){return this.channels[e].getHandler()}},{key:"setHandler",value:function(e,t){this.channels[e].setHandler(t)}},{key:"addData",value:function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,function(){return"["+il([t[e],t[e+1]])+"] -> ("+il([i,n])+")"});var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return cl(null,null,o),r.logger.log(3,function(){return"Repeated command ("+il([i,n])+") is dropped"}),0;cl(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else cl(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;if(l&&l>0)r.channels[l].insertChars(s);else r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,function(){return"Couldn't parse cleaned data "+il([i,n])+" orig: "+il([t[e],t[e+1]])})},n=0;n<t.length;n+=2)i(n)}},{key:"parseCmd",value:function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0}},{key:"parseMidrow",value:function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+il([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;r=t>=64&&t<=95?1===i?$o[e]:Zo[e]:1===i?Jo[e]:el[e];var n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0)}},{key:"interpretPAC",value:function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=!(1&~r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r,i,n=null,a=null;(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19)?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+zo(i)+"' in channel "+r}),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,function(){return"Char codes = "+il(n).join(",")}),n}},{key:"parseBackgroundAttributes",value:function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=tl[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(i),!0}},{key:"reset",value:function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}cl(null,null,this.cmdHistory)}},{key:"cueSplitAtTime",value:function(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}}}])}();function cl(e,t,r){r.a=e,r.b=t}var dl=function(){if(null!=di&&di.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var s in a)e[s]=a[s]}return e}function a(t,a,s){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var u="",c=!1,d=t,h=a,f=s,v=null,g="",p=!0,m="auto",y="start",E=50,k="middle",T=50,S="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return v},set:function(e){v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return g},set:function(t){var i=function(t){return r(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");g=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return k},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");k=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),hl=function(){return o(function e(){a(this,e)},[{key:"decode",value:function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}])}();function fl(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var vl=function(){return o(function e(){a(this,e),this.values=Object.create(null)},[{key:"set",value:function(e,t){this.get(e)||""===t||(this.values[e]=t)}},{key:"get",value:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}}},{key:"integer",value:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}},{key:"percent",value:function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}])}();function gl(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);if(2===s.length)t(s[0],s[1])}}var pl=new dl(0,0,""),ml="middle"===pl.align?"middle":"center";function yl(e,t,r){var i=e;function n(){var t=fl(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new vl;gl(e,function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",ml,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",ml,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",ml,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===pl.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",ml);var a=i.get("position","auto");"auto"===a&&50===pl.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function El(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var kl=function(){return o(function e(){a(this,e),this.state="INITIAL",this.buffer="",this.decoder=new hl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0},[{key:"parse",value:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=El(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),i}function i(e){gl(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var n="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var a=(n=r()).match(/^()?WEBVTT([ \t].*)?$/);if(null==a||!a[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:n=r(),t.state){case"HEADER":/:/.test(n)?i(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new dl(0,0,""),t.state="CUE",-1===n.indexOf("--\x3e")){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{yl(n,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var o=-1!==n.indexOf("--\x3e");if(!n||o&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=n;continue;case"BADCUE":n||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}},{key:"flush",value:function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}])}(),Tl=/\r\n|\n\r|\n|\r/g,Sl=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return e.slice(r,r+t.length)===t};function bl(e,t,r){return Po(e.toString())+Po(t.toString())+Po(r)}function Al(e,t,r,i,n,a,s){var o,l=new kl,u=be(new Uint8Array(e)).trim().replace(Tl,"\n").split("\n"),c=[],d=t?function(e){return Na(e,9e4,1/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1))}(t.baseTime,t.timescale):0,h="00:00.000",f=0,v=0,g=!0;l.oncue=function(e){var a=r[i],s=r.ccOffset,l=(f-d)/9e4;if(null!=a&&a.new&&(void 0!==v?s=r.ccOffset=a.start:function(e,t,r){var i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!=(a=n)&&a.new;){var a;e.ccOffset+=i.start-n.start,i.new=!1,n=e[(i=n).prevCC]}e.presentationOffset=r}(r,i,l)),l){if(!t)return void(o=new Error("Missing initPTS for VTT MPEGTS"));s=l-r.presentationOffset}var u=e.endTime-e.startTime,h=ja(9e4*(e.startTime+s-v),9e4*n)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+u,0);var g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=bl(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},l.onparsingerror=function(e){o=e},l.onflush=function(){o?s(o):a(c)},u.forEach(function(e){if(g){if(Sl(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach(function(e){Sl(e,"LOCAL:")?h=e.slice(6):Sl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{v=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(X(t)&&X(r)&&X(i)&&X(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*r,t+=6e4*i,t+36e5*n}(h)/1e3}catch(e){o=e}return}""===e&&(g=!1)}l.parse(e+"\n")}),l.flush()}var Ll="stpp.ttml.im1t",Il=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,wl={left:"start",center:"center",right:"end",start:"start",end:"end"};function Pl(e,t,r,i){var n=qe(new Uint8Array(e),["mdat"]);if(0!==n.length){var a=n.map(function(e){return be(e)}),s=function(e,t){return Na(e,t,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}(t.baseTime,1,t.timescale);try{a.forEach(function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce(function(e,t){return e[t]=i.getAttribute("ttp:".concat(t))||n[t],e},{}),s="preserve"!==i.getAttribute("xml:space"),o=Dl(xl(i,"styling","style")),l=Dl(xl(i,"layout","region")),u=xl(i,"body","[begin]");return[].map.call(u,function(e){var r=Cl(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=Ol(e.getAttribute("begin"),a),n=Ol(e.getAttribute("dur"),a),u=Ol(e.getAttribute("end"),a);if(null===i)throw Ml(e);if(null===u){if(null===n)throw Ml(e);u=i+n}var c=new dl(i-t,u-t,r);c.id=bl(c.startTime,c.endTime,c.text);var d=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;s&&r.hasOwnProperty(s)&&(n=r[s]);return a.reduce(function(r,a){var s=_l(t,i,a)||_l(e,i,a)||_l(n,i,a);return s&&(r[a]=s),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),h=d.textAlign;if(h){var f=wl[h];f&&(c.lineAlign=f),c.align=h}return de(c,d),c}).filter(function(e){return null!==e})}(e,s))})}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function xl(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Dl(e){return e.reduce(function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function Cl(e,t){return[].slice.call(e.childNodes).reduce(function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?Cl(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function _l(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Ml(e){return new Error("Could not parse ttml timestamp ".concat(e))}function Ol(e,t){if(!e)return null;var r=fl(e);return null===r&&(Il.test(e)?r=function(e,t){var r=Il.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):Rl.test(e)&&(r=function(e,t){var r=Rl.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}var Fl=function(){return o(function e(t,r){a(this,e),this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r},[{key:"dispatchCue",value:function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}},{key:"newCue",value:function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}},{key:"reset",value:function(){this.cueRanges=[],this.startTime=null}}])}(),Nl=function(){return o(function e(t){a(this,e),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ee.FRAG_LOADING,this.onFragLoading,this),t.on(ee.FRAG_LOADED,this.onFragLoaded,this),t.on(ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ee.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)},[{key:"destroy",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this),e.off(ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(ee.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}},{key:"initCea608Parsers",value:function(){var e=new Fl(this,"textTrack1"),t=new Fl(this,"textTrack2"),r=new Fl(this,"textTrack3"),i=new Fl(this,"textTrack4");this.cea608Parser1=new ul(1,e,t),this.cea608Parser2=new ul(3,r,i)}},{key:"addCues",value:function(e,t,r,i,n){for(var a=!1,s=n.length;s--;){var o=n[s],l=Gl(o[0],o[1],t,r);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),a=!0,l/(r-t)>.5))return}if(a||n.push([t,r]),this.config.renderTextTracksNatively){var u=this.captionsTracks[e];this.Cues.newCue(u,t,r,i)}else{var c=this.Cues.newCue(null,t,r,i);this.hls.trigger(ee.CUES_PARSED,{type:"captions",cues:c,track:e})}}},{key:"onInitPtsFound",value:function(e,t){var r=this,i=t.frag,n=t.id,a=t.initPTS,s=t.timescale,o=t.trackId,l=this.unparsedVttFrags;n===ae&&(this.initPTS[i.cc]={baseTime:a,timescale:s,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach(function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(ee.FRAG_LOADED,e):r.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}},{key:"getExistingTrack",value:function(e,t){var r=this.media;if(r)for(var i=0;i<r.textTracks.length;i++){var n=r.textTracks[i];if(Bl(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}},{key:"createCaptionsTrack",value:function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}},{key:"createNativeTrack",value:function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.media,n=t[e],a=n.label,s=n.languageCode,o=this.getExistingTrack(a,s);if(o)r[e]=o,Lo(r[e]),bo(r[e],i);else{var l=this.createTextTrack("captions",a,s);l&&(l[e]=!0,r[e]=l)}}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}}},{key:"createTextTrack",value:function(e,t,r){var i=this.media;if(i)return i.addTextTrack(e,t,r)}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){var i=this.captionsTracks;Object.keys(i).forEach(function(e){Lo(i[e]),delete i[e]}),this.nonNativeCaptionsTracks={}}}},{key:"onManifestLoading",value:function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{key:"_cleanTracks",value:function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var r=0;r<t.length;r++)Lo(t[r])}}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks||[],n=i.some(function(e){return e.textCodec===Ll});if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(os(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){var a=this.media,s=a?Ro(a.textTracks):null;if(this.tracks.forEach(function(e,t){var i;if(s){for(var n=null,a=0;a<s.length;a++)if(s[a]&&Bl(s[a],e)){n=s[a],s[a]=null;break}n&&(i=n)}if(i)Lo(i);else{var o=Ul(e);(i=r.createTextTrack(o,e.name,e.lang))&&(i.mode="disabled")}i&&r.textTracks.push(i)}),null!=s&&s.length){var o=s.filter(function(e){return null!==e}).map(function(e){return e.label});o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: ".concat(o.join(", "),". Replace media element for each source to clear TextTracks and captions menu."))}}else if(this.tracks.length){var l=this.tracks.map(function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}});this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}},{key:"onManifestLoaded",value:function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack".concat(t[1]),n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}})}},{key:"closedCaptionsForLevel",value:function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}},{key:"onFragLoading",value:function(e,t){if(this.enabled&&t.frag.type===ae){var r,i,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(r=null==(i=t.part)?void 0:i.index)?r:-1;n&&a&&(u!==s+1||u===s&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}},{key:"onFragLoaded",value:function(e,t){var r=t.frag,i=t.payload;if(r.type===oe)if(i.byteLength){var n=r.decryptdata,a="stats"in t;if(null==n||!n.encrypted||a){var s=this.tracks[r.level],o=this.vttCCs;o[r.cc]||(o[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),s&&s.textCodec===Ll?this._parseIMSC1(r,i):this._parseVTTs(t)}}else this.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}},{key:"_parseIMSC1",value:function(e,t){var r=this,i=this.hls;Pl(t,this.initPTS[e.cc],function(t){r._appendCues(t,e.level),i.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},function(t){i.logger.log("Failed to parse IMSC1: ".concat(t)),i.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}},{key:"_parseVTTs",value:function(e){var t,r=this,i=e.frag,n=e.payload,a=this.initPTS,s=this.unparsedVttFrags,o=a.length-1;if(a[i.cc]||-1!==o){var l=this.hls;Al(null!=(t=i.initSegment)&&t.data?it(i.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,function(e){r._appendCues(e,i.level),l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},function(t){var a="Missing initPTS for VTT MPEGTS"===t.message;a?s.push(e):r._fallbackToIMSC1(i,n),l.logger.log("Failed to parse VTT cue: ".concat(t)),a&&o>i.cc||l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}else s.push(e)}},{key:"_fallbackToIMSC1",value:function(e,t){var r=this,i=this.tracks[e.level];i.textCodec||Pl(t,this.initPTS[e.cc],function(){i.textCodec=Ll,r._parseIMSC1(e,t)},function(){i.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(function(e){return Ao(i,e)})}else{var n=this.tracks[t];if(!n)return;var a=n.default?"default":"subtitles"+t;r.trigger(ee.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}},{key:"onFragDecrypted",value:function(e,t){t.frag.type===oe&&this.onFragLoaded(ee.FRAG_LOADED,t)}},{key:"onSubtitleTracksCleared",value:function(){this.tracks=[],this.captionsTracks={}}},{key:"onFragParsingUserdata",value:function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,i=t.samples;if(r.type!==ae||"NONE"!==this.closedCaptionsForLevel(r))for(var n=0;n<i.length;n++){var a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,s[0]),this.cea608Parser2.addData(i[n].pts,s[1])}}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<i)){if(!a||"video"===a){var o=this.captionsTracks;Object.keys(o).forEach(function(e){return Io(o[e],r,i)})}if(this.config.renderTextTracksNatively&&0===r&&void 0!==n){var l=this.textTracks;Object.keys(l).forEach(function(e){return Io(l[e],r,n)})}}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],r=31&e[0],i=2,n=0;n<r;n++){var a=e[i++],s=127&e[i++],o=127&e[i++];if(0!==s||0!==o)if(!!(4&a)){var l=3&a;0!==l&&1!==l||(t[l].push(s),t[l].push(o))}}return t}}])}();function Ul(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Bl(e,t){return!!e&&e.kind===Ul(t)&&us(t,e)}function Gl(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}var Hl=/\s/,Vl={newCue:function(e,t,r,i){for(var n,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<i.rows.length;d++)if(s=!0,o=0,l="",!(n=i.rows[d]).isEmpty()){for(var h,f=0;f<n.chars.length;f++)Hl.test(n.chars[f].uchar)&&s?o++:(l+=n.chars[f].uchar,s=!1);n.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;var v=El(l.trim()),g=bl(t,r,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,r,v)).id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort(function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line}),u.forEach(function(t){return Ao(e,t)})),u}};var Kl=/(\d+)-(\d+)\/(\d+)/,jl=function(){return o(function e(t){a(this,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=t.fetchSetup||Yl,this.controller=new self.AbortController,this.stats=new xe},[{key:"destroy",value:function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}},{key:"abortInternal",value:function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}},{key:"load",value:function(e,t,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var a=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(de({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),s="arraybuffer"===e.responseType,o=s?"byteLength":"length",l=t.loadPolicy,u=l.maxTimeToFirstByteMs,c=l.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&X(u)?u:c,this.requestTimeout=self.setTimeout(function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))},t.timeout),(es(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(r){var a;i.response=i.loader=r;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(i.requestTimeout),t.timeout=c,i.requestTimeout=self.setTimeout(function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))},c-(o-n.loading.start)),!r.ok){var l=r.status,u=r.statusText;throw new Wl(u||"fetch, bad network response",l,r)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=Kl.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(X(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||n.total;var d=null==(a=i.callbacks)?void 0:a.onProgress;return d&&X(t.highWaterMark)?i.loadProgressively(r,n,e,t.highWaterMark,d):s?r.arrayBuffer():"json"===e.responseType?r.json():r.text()}).then(function(r){var a,s,l=i.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=r[o];u&&(n.loaded=n.total=u);var c={url:l.url,data:r,code:l.status},d=null==(a=i.callbacks)?void 0:a.onProgress;d&&!X(t.highWaterMark)&&d(n,e,r,l),null==(s=i.callbacks)||s.onSuccess(c,n,e,l)}).catch(function(t){var r;if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=t&&t.code||0,s=t?t.message:null;null==(r=i.callbacks)||r.onError({code:a,text:s},e,t?t.details:null,n)}})}},{key:"getCacheAge",value:function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.response?this.response.headers.get(e):null}},{key:"loadProgressively",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4?arguments[4]:void 0,a=new Ln,s=e.body.getReader(),o=function(){return s.read().then(function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<i||a.dataLength?(a.push(l),a.dataLength>=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}();function Yl(e,t){return new self.Request(e.url,t)}var Wl=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e])).code=void 0,s.details=void 0,s.code=r,s.details=i,s}return d(t,e),o(t)}(L(Error)),ql=/^age:\s*[\d.]+\s*$/im,zl=function(){return o(function e(t){a(this,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=t&&t.xhrSetup||null,this.stats=new xe,this.retryDelay=0},[{key:"destroy",value:function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}},{key:"abortInternal",value:function(){var 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()))}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}},{key:"load",value:function(e,t,r){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=r,this.loadInternal()}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then(function(){if(e.loader===i&&!e.stats.aborted)return a(i,r.url)}).catch(function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a(i,r.url)}).then(function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)}):this.openAndSendXhr(i,r,t)}}},{key:"openAndSendXhr",value:function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);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),r.timeout=a&&X(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=c,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var h={url:t.responseURL,data:o,code:a};return void(null==(u=this.callbacks)||u.onSuccess(h,r,e,t))}}var f,v=n.loadPolicy.errorRetry;if(cr(v,r.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else ke.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,r)}}}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(cr(e,this.stats.retry,!0))this.retry(e);else{var t;ke.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}}},{key:"retry",value:function(e){var t=this.context,r=this.stats;this.retryDelay=lr(e,r.retry),r.retry++,ke.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==t?void 0:t.url,", retrying ").concat(r.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}},{key:"loadprogress",value:function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}},{key:"getCacheAge",value:function(){var e=null;if(this.loader&&ql.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.loader&&new RegExp("^".concat(e,":\\s*[\\d.]+\\s*$"),"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}])}(),Xl=fe(fe({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:zl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Jt,bufferController:gs,capLevelController:ys,errorController:kr,fpsController:So,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:Ti,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},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:Vl,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:Yo,subtitleTrackController:wo,timelineController:Nl,audioStreamController:as,audioTrackController:cs,emeController:mo,cmcdController:fo,contentSteeringController:vo,interstitialsController:jo});function Ql(e){return e&&"object"===S(e)?Array.isArray(e)?e.map(Ql):Object.keys(e).reduce(function(t,r){return t[r]=Ql(e[r]),t},{}):e}function $l(e,t){var r=e.loader;r!==jl&&r!==zl?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=jl,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Jl=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["gap-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(ee.MEDIA_ENDED,{stalled:!1}))},i.hls=e,i.fragmentTracker=r,i.registerListeners(),i}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"destroy",value:function(){E(t,"destroy",this,3)([]),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}},{key:"onMediaAttached",value:function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;ln(r,"playing",this.onMediaPlaying),ln(r,"waiting",this.onMediaWaiting),ln(r,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var r=this.media;r&&(un(r,"playing",this.onMediaPlaying),un(r,"waiting",this.onMediaWaiting),un(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}},{key:"onBufferAppended",value:function(e,t){this.buffered=t.timeRanges}},{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}},{key:"tick",value:function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}}},{key:"poll",value:function(e,t){var r,i,n=null==(r=this.hls)?void 0:r.config;if(n){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(ee.MEDIA_ENDED,{stalled:!1})));if(jr.getBuffered(a).length){var c=jr.bufferInfo(a,e,0),d=c.nextStart||0,h=this.fragmentTracker;if(s&&h&&this.hls){var f=Zl(this.hls.inFlightFragments,e),v=c.len>2,g=!d||f||d-e>2&&!h.getPartialFragment(e);if(v||g)return;this.moved=!1}var p=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!d)return;var m=Math.max(d,c.start||0)-e,y=!(null==p||!p.live)?2*p.targetduration:2,E=tu(e,h);if(m>0&&(m<=y||E))return void(a.paused||this._trySkipBufferHole(E))}var k=n.detectStallWithCurrentTimeMs,T=self.performance.now(),S=this.waiting,b=this.stalled;if(null===b){if(!(S>0&&T-S<k))return void(this.stalled=T);b=this.stalled=S}var A=T-b;if(!s&&(A>=k||S)&&this.hls){var L;if("ended"===(null==(L=this.mediaSource)?void 0:L.readyState)&&(null==p||!p.live)&&Math.abs(e-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(ee.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}var I=jr.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(I,A,e)}else this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(r),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(ee.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=jr.bufferedInfo(jr.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=jr.timeRangesToArray(i),s=jr.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=jr.bufferedInfo(a,e,0).bufferedIndex,l=a[s].end,u=a[s+1].start;if((-1===o||o>s)&&u-l<1&&e-l<2){var c=new Error("nudging playhead to flush pipeline after video hole. currentTime: ".concat(e," hole: ").concat(l," -> ").concat(u," buffered index: ").concat(o));this.warn(c.message),this.media.currentTime+=1e-6;var d=tu(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var h=jr.bufferInfo(this.media,e,0);this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:d,buffer:h.len,bufferInfo:h})}}}}}},{key:"_tryFixBufferStall",value:function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=tu(r,a);if(u||null!=l&&l.live&&r<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}}},{key:"adjacentTraversal",value:function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,ae),a=r.getFragAtPos(i,ae);if(n&&a)return a.sn-n.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(r.currentTime," due to low buffer (").concat(Kt(e),")"));this.warn(a.message),t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}},{key:"_trySkipBufferHole",value:function(e){var t,r=this.fragmentTracker,i=this.media,n=null==(t=this.hls)?void 0:t.config;if(!i||!r||!n)return 0;var a=i.currentTime,s=jr.bufferInfo(i,a,0),o=a<s.start?s.start:s.nextStart;if(o&&this.hls){var l=s.len<=n.maxBufferHole,u=s.len>0&&s.len<1&&i.readyState<3,c=o-a;if(c>0&&(l||u)){if(c>n.maxBufferHole){var d=!1;if(0===a){var h=r.getAppendedFrag(0,ae);h&&o<h.end&&(d=!0)}if(!d&&e){var f;if(null==(f=this.hls.loadLevelObj)||!f.details)return 0;if(Zl(this.hls.inFlightFragments,o))return 0;for(var v=!1,g=e.end;g<o;){var p=tu(g,r);if(!p){v=!0;break}g+=p.duration}if(v)return 0}}var m=Math.max(o+.05,a+.1);if(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(m)),this.moved=!0,i.currentTime=m,null==e||!e.gap){var y=new Error("fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(m)),E={type:J.MEDIA_ERROR,details:Z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?E.part=e:E.frag=e),this.hls.trigger(ee.ERROR,E)}return m}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,n=null==t?void 0:t.config;if(!r||!n)return 0;var a=r.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){var s=a+(i+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),r.currentTime=s,t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @".concat(a," after ").concat(n.nudgeMaxRetry," nudges"));this.error(l.message),t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}])}(Hr);function Zl(e,t){var r=eu(e.main);if(r&&r.start<=t)return r;var i=eu(e.audio);return i&&i.start<=t?i:null}function eu(e){if(!e)return null;switch(e.state){case hn:case dn:case En:case kn:return null}return e.frag}function tu(e,t){return t.getAppendedFrag(e,ae)||t.getPartialFragment(e)}function ru(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function iu(e,t,r,i,n){var a=new e(t,r,"");try{a.value=i,n&&(a.type=n)}catch(s){a=new e(t,r,Kt(n?fe({type:n},i):i))}return a}var nu=function(){var e=ru();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),au=function(){return o(function e(t){var r=this;a(this,e),this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){r.hls&&r.hls.trigger(ee.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()},[{key:"destroy",value:function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}},{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"onMediaAttaching",value:function(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}},{key:"onMediaAttached",value:function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}},{key:"onMediaDetaching",value:function(e,t){this.media=null,!!t.transferMedia||(this.id3Track&&(this.removeCues&&Lo(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}},{key:"onManifestLoading",value:function(){this.dateRangeCuesAppended={}}},{key:"createTrack",value:function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t}},{key:"getID3Track",value:function(e){if(this.media){for(var t=0;t<e.length;t++){var r=e[t];if("metadata"===r.kind&&"id3"===r.label)return bo(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var r=this.hls.config,i=r.enableEmsgMetadataCues,n=r.enableID3MetadataCues;if(i||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=ru();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==Zn.emsg||i)&&n){var u=Xn(a[o].data),c=a[o].pts,d=c+a[o].duration;d>nu&&(d=nu),d-c<=0&&(d=c+.25);for(var h=0;h<u.length;h++){var f=u[h];if(!Qn(f)){this.updateId3CueEnds(c,l);var v=iu(s,c,d,f,l);v&&this.id3Track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(var n=i.length;n--;){var a=i[n];a.type===t&&a.startTime<e&&a.endTime===nu&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.type,a=this.id3Track,s=this.hls;if(s){var o=s.config,l=o.enableEmsgMetadataCues,u=o.enableID3MetadataCues;if(a&&(l||u))Io(a,r,i,"audio"===n?function(e){return e.type===Zn.audioId3&&u}:"video"===n?function(e){return e.type===Zn.emsg&&l}:function(e){return e.type===Zn.audioId3&&u||e.type===Zn.emsg&&l})}}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=ru();if(n&&a&&!o){var u=e.fragmentStart,c=e.fragmentEnd,d=this.assetCue;d?(d.startTime=u,d.endTime=c):l&&(d=this.assetCue=iu(l,u,c,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var h,f=this.id3Track,v=e.dateRanges,g=Object.keys(v),p=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.cues)&&h.length)for(var m,y=Object.keys(p).filter(function(e){return!g.includes(e)}),E=function(){var e=y[k],t=null==(m=p[e])?void 0:m.cues;delete p[e],t&&Object.keys(t).forEach(function(e){var i=t[e];if(i){i.removeEventListener("enter",r.onEventCueEnter);try{f.removeCue(i)}catch(e){}}})},k=y.length;k--;)E();else p=this.dateRangeCuesAppended={};var T=e.fragments[e.fragments.length-1];if(0!==g.length&&X(null==T?void 0:T.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=g[b],t=v[e],i=t.startTime,n=p[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=nu,c=t.duration;if(t.endDate&&null!==c)u=i+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,r){if(r!==t.id){var i=v[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var m=h[f];if(Zr(m)){var y=a[m];if(y)!s||null!=n&&n.durationKnown?Math.abs(y.startTime-i)>.01&&(y.startTime=i,y.endTime=u):y.endTime=u;else if(l){var E=t.attr[m];ei(m)&&(E=Le(E));var k=iu(l,i,u,{key:m,data:E},Zn.dateRange);k&&(k.id=e,r.id3Track.addCue(k),a[m]=k,o&&("X-ASSET-LIST"!==m&&"X-ASSET-URL"!==m||k.addEventListener("enter",r.onEventCueEnter)))}}}p[e]={cues:a,dateRange:t,durationKnown:s}},b=0;b<g.length;b++)S()}}}}}}])}(),su=function(){return o(function e(t){var r=this;a(this,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=function(){var e=r.media,t=r.levelDetails;if(e&&t){r.currentTime=e.currentTime;var i=r.computeLatency();if(null!==i){r._latency=i;var n=r.config,a=n.lowLatencyMode,s=n.maxLiveSyncPlaybackRate;if(a&&1!==s&&t.live){var o=r.targetLatency;if(null!==o){var l=i-o;if(l<Math.min(r.maxLatency,o+t.targetduration)&&l>.05&&r.forwardBufferLength>1){var u=Math.min(2,Math.max(1,s)),c=Math.round(2/(1+Math.exp(-.75*l-r.edgeStalled))*20)/20,d=Math.min(u,Math.max(1,c));r.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&r.changeMediaPlaybackRate(e,1)}}}}},this.hls=t,this.config=t.config,this.registerListeners()},[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var c=i;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.ERROR,this.onError,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.ERROR,this.onError,this))}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}},{key:"onManifestLoading",value:function(){this._latency=null,this.stallCount=0}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onError",value:function(e,t){var r;t.details===Z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(i=this.targetLatency)?void 0:i.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(e.playbackRate," to ").concat(t)),e.playbackRate=t)}},{key:"estimateLiveEdge",value:function(){var e=this.levelDetails;return null===e?null:e.edge+e.age}},{key:"computeLatency",value:function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}])}(),ou=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[e,"level-controller"]))._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}return d(t,e),o(t,[{key:"_registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.ERROR,this.onError,this)}},{key:"_unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.ERROR,this.onError,this)}},{key:"destroy",value:function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),E(t,"destroy",this,3)([])}},{key:"stopLoad",value:function(){this._levels.forEach(function(e){e.loadError=0,e.fragmentError=0}),E(t,"stopLoad",this,3)([])}},{key:"resetLevels",value:function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}},{key:"onManifestLoading",value:function(e,t){this.resetLevels()}},{key:"onManifestLoaded",value:function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1;t.levels.forEach(function(e){var t=e.attrs,c=e.audioCodec,d=e.videoCodec;c&&(e.audioCodec=c=Tt(c,i)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");i.length>2&&"avc1"===i[0]&&(t[r]="avc1.".concat(parseInt(i[1]).toString(16)).concat(("000"+parseInt(i[2]).toString(16)).slice(-4)))}return t.join(",")}(d));var h=e.width,f=e.height,v=e.unknownCodecs,g=(null==v?void 0:v.length)||0;if(o||(o=!(!h||!f)),l||(l=!!d),u||(u=!!c),g||c&&!r.isAudioSupported(c)||d&&!r.isVideoSupported(d))r.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'));else{var p=t.CODECS,m=t["FRAME-RATE"],y=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],k=t.RESOLUTION,T=t["VIDEO-RANGE"],S="".concat(E||".","-"),b="".concat(S).concat(e.bitrate,"-").concat(k,"-").concat(m,"-").concat(p,"-").concat(T,"-").concat(y);if(a[b])if(a[b].uri===e.url||e.attrs["PATHWAY-ID"])a[b].addGroupId("audio",t.AUDIO),a[b].addGroupId("text",t.SUBTITLES);else{var A=s[b]+=1;e.attrs["PATHWAY-ID"]=new Array(A+1).join(".");var L=r.createLevel(e);a[b]=L,n.push(L)}else{var I=r.createLevel(e);a[b]=I,s[b]=1,n.push(I)}}}),this.filterAndSortMediaOptions(n,t,o,l,u)}},{key:"createLevel",value:function(e){var t=new Gt(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(r.videoCodec,'"'));this.log(i.message),t.supportedResult=Pt(i,[])}return t}},{key:"isAudioSupported",value:function(e){return vt(e,"audio",this.hls.config.preferManagedMediaSource)}},{key:"isVideoSupported",value:function(e){return vt(e,"video",this.hls.config.preferManagedMediaSource)}},{key:"filterAndSortMediaOptions",value:function(e,t,r,i,n){var a,s=this,o=[],l=[],u=e,c=(null==(a=t.stats)?void 0:a.parsing)||{};if((r||i)&&n&&(u=u.filter(function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&(!!(t=i)&&Mt.indexOf(t)>-1)})),0===u.length)return Promise.resolve().then(function(){if(s.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: ".concat(Kt(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,r){return r.indexOf(e)===t}))),s.warn(r),e+=" (".concat(r,")"));var i=new Error(e);s.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}),void(c.end=performance.now());t.audioTracks&&lu(o=t.audioTracks.filter(function(e){return!e.audioCodec||s.isAudioSupported(e.audioCodec)})),t.subtitles&&lu(l=t.subtitles);var d=u.slice(0);u.sort(function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&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 Mt.indexOf(e.videoRange)-Mt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=mt(e.videoCodec),n=mt(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=yt(e.codecSet),s=yt(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});var h=d[0];if(this.steering&&(u=this.steering.filterParsedLevels(u)).length!==d.length)for(var f=0;f<d.length;f++)if(d[f].pathwayId===u[0].pathwayId){h=d[f];break}this._levels=u;for(var v=0;v<u.length;v++)if(u[v]===h){var g;this._firstLevel=v;var p=h.bitrate,m=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(u.length," level(s) found, first bitrate: ").concat(p)),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){var y=Math.min(p,this.hls.config.abrEwmaDefaultEstimateMax);y>m&&m===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var E=n&&!i,k=this.hls.config,T=!(!k.audioStreamController||!k.audioTrackController),S={levels:u,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:T&&!E&&o.some(function(e){return!!e.url})};c.end=performance.now(),this.hls.trigger(ee.MANIFEST_PARSED,S)}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level ".concat(e," (").concat(o.height?o.height+"p ":"").concat(o.videoRange?o.videoRange+" ":"").concat(o.codecSet?o.codecSet+" ":"","@").concat(o.bitrate,")").concat(l?" with Pathway "+l:""," from level ").concat(n).concat(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(ee.LEVEL_SWITCHING,u);var c=o.details;if(!c||c.live){var d=this.switchParams(o.uri,null==a?void 0:a.details,c);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter(function(e){return-1!==t.indexOf(e)});if(e.length<1)return void this.warn("pathwayPriority ".concat(e," should contain at least one pathway from list: ").concat(t));this.steering.pathwayPriority=r}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===re&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var r=t.frag;if(void 0!==r&&r.type===ae){var i=r.elementaryStreams;if(!Object.keys(i).some(function(e){return!!i[e]}))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of ".concat(n.loadError," on frag buffered")),n.loadError=0)}}},{key:"onLevelLoaded",value:function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(n)),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)}},{key:"loadPlaylist",value:function(e){E(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}},{key:"loadingPlaylist",value:function(e,r){E(t,"loadingPlaylist",this,3)([e,r]);var i=this.getUrlWithDirectives(e.uri,r),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],s=e.details,o=null==s?void 0:s.age;this.log("Loading level index ".concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(i)),this.hls.trigger(ee.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}},{key:"removeLevel",value:function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter(function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});Zi(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(ee.LEVELS_UPDATED,{levels:i})}}},{key:"onLevelsUpdated",value:function(e,t){var r=t.levels;this._levels=r}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(ee.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}])}(ss);function lu(e){var t={};e.forEach(function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}function uu(){return self.SourceBuffer||self.WebKitSourceBuffer}function cu(){if(!Te())return!1;var e=uu();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var du=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"stream-controller",ae])).audioCodecSwap=!1,s.level=-1,s._forceStartLoad=!1,s._hasEnoughToStart=!1,s.altAudio=0,s.audioOnly=!1,s.fragPlaying=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s.onMediaPlaying=function(){s.tick()},s.onMediaSeeked=function(){var e=s.media,t=e?e.currentTime:null;if(null!==t&&X(t)&&(s.log("Media seeked to ".concat(t.toFixed(3))),s.getBufferedFrag(t))){var r=s.getFwdBufferInfoAtPos(e,t,ae,0);null!==r&&0!==r.len?s.tick():s.warn("Main forward buffer length at ".concat(t,' on "seeked" event ').concat(r?r.len:"empty",")"))}},s.registerListeners(),s}return d(t,e),o(t,[{key:"registerListeners",value:function(){E(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){E(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"onHandlerDestroying",value:function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),E(t,"onHandlerDestroying",this,3)([])}},{key:"startLoad",value:function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=i.startLevel;-1===n&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r),this.state=hn,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=dn}},{key:"stopLoad",value:function(){this._forceStartLoad=!1,E(t,"stopLoad",this,3)([])}},{key:"doTick",value:function(){switch(this.state){case Sn:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=hn;break}if(this.hls.nextLoadLevel!==this.level){this.state=hn;break}break;case gn:this.checkRetryDate()}this.state===hn&&this.doTickIdle(),this.onTickEnd()}},{key:"onTickEnd",value:function(){var e;E(t,"onTickEnd",this,3)([]),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}},{key:"doTickIdle",value:function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(ee.BUFFER_EOS,l),void(this.state=En)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level ".concat(n," from level ").concat(this.level)),this.level=e.nextLoadLevel=n;var u=a.details;if(!u||this.state===Sn||this.waitForLive(a))return this.level=n,this.state=Sn,void(this.startFragRequested=!1);var c=s.len,d=this.getMaxBufferLength(a.maxBitrate);if(!(c>=d)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);var h=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&Oe(f)&&this.fragmentTracker.getState(f)!==Lr){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,p=u.fragments[g-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?De:Ce,y=(m===Ce?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,ae)}f=this.getNextFragmentLoopLoading(f,u,s,ae,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}}}}}}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n===Sr||n===Ar?Oe(e)?this.bitrateTest?(this.log("Fragment ".concat(e.sn," of level ").concat(e.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(e,r)):E(t,"loadFragment",this,3)([e,r,i]):this._loadInitSegment(e,r):this.clearTrackerIfNeeded(e)}},{key:"getBufferedFrag",value:function(e){return this.fragmentTracker.getBufferedFrag(e,ae)}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.end+.5):null}},{key:"immediateLevelSwitch",value:function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}},{key:"nextLevelSwitch",value:function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var a=this.getMainFwdBufferInfo();if(!a||a.len<2*n.targetduration)return}if(!t.paused&&e){var s=e[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);if(l){var u=this.followingBufferedFrag(l);if(u){this.abortCurrentFrag();var c=u.maxStartPTS?u.maxStartPTS:u.start,d=u.duration,h=Math.max(l.end,c+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}},{key:"abortCurrentFrag",value:function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case fn:case vn:case gn:case mn:case yn:this.state=hn}this.nextLoadPosition=this.getLoadPosition()}},{key:"flushMainBuffer",value:function(e,r){E(t,"flushMainBuffer",this,3)([e,r,2===this.altAudio?"video":null])}},{key:"onMediaAttached",value:function(e,r){E(t,"onMediaAttached",this,3)([e,r]);var i=r.media;ln(i,"playing",this.onMediaPlaying),ln(i,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,r){var i=this.media;i&&(un(i,"playing",this.onMediaPlaying),un(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,E(t,"onMediaDetaching",this,3)([e,r]),!!r.transferMedia||(this._hasEnoughToStart=!1)}},{key:"onManifestLoading",value:function(){E(t,"onManifestLoading",this,3)([]),this.log("Trigger BUFFER_RESET"),this.hls.trigger(ee.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}},{key:"onManifestParsed",value:function(e,t){for(var r,i,n=!1,a=!1,s=0;s<t.levels.length;s++){var o=t.levels[s].audioCodec;o&&(n=n||-1!==o.indexOf("mp4a.40.2"),a=a||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=n&&a&&!("function"==typeof(null==(i=uu())||null==(r=i.prototype)?void 0:r.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}},{key:"onLevelLoading",value:function(e,t){if(this.levels&&this.state===hn){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Sn)}}},{key:"onLevelLoaded",value:function(e,t){var r,i=this.levels,n=this.startFragRequested,a=t.level,s=t.details,o=s.totalduration;if(i){this.log("Level ".concat(a," loaded [").concat(s.startSN,",").concat(s.endSN,"]").concat(s.lastPartSn?"[part-".concat(s.lastPartSn,"-").concat(s.lastPartIndex,"]"):"",", cc [").concat(s.startCC,", ").concat(s.endCC,"] duration:").concat(o));var l=t.levelInfo,u=this.fragCurrent;!u||this.state!==vn&&this.state!==gn||u.level!==t.level&&u.loader&&this.abortCurrentFrag();var c=0;if(s.live||null!=(r=l.details)&&r.live){var d;if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;c=this.alignPlaylists(s,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=s,this.levelLastLoaded=l,n||this.setStartPosition(s,c),this.hls.trigger(ee.LEVEL_UPDATED,{details:s,level:a}),this.state===Sn){if(this.waitForCdnTuneIn(s))return;this.state=hn}n&&s.live&&this.synchronizeToLiveEdge(s),this.tick()}else this.warn("Levels were reset while loading level ".concat(a))}},{key:"synchronizeToLiveEdge",value:function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn("Playback: ".concat(n.toFixed(3)," is located too far from the end of live sliding playlist: ").concat(s,", reset currentTime to : ").concat(i.toFixed(3))),"buffered"===this.config.liveSyncMode){var u,c=jr.bufferInfo(r,i,0);if(null==(u=c.buffered)||!u.length)return void(r.currentTime=i);if(c.start<=n)return void(r.currentTime=i);var d=jr.bufferedInfo(c.buffered,n,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=i}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(r.sn," of level ").concat(r.level," after level details were reset")),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(s),h=this.transmuxer=this.transmuxer||new ns(this.hls,ae,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,v=-1!==f,g=new Vr(r.level,r.sn,r.stats.chunkCount,n.byteLength,f,v),p=this.initPTS[r.cc];h.push(n,c,d,l,r,i,o.totalduration,u,g,p)}else this.warn("Level ".concat(r.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var r=this,i=this.hls,n=2===this.altAudio;if($t(t.url,i))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;var a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.fragmentTracker.removeAllFragments(),i.once(ee.BUFFER_FLUSHED,function(){r.hls&&r.hls.trigger(ee.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(ee.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var r=$t(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?2:0,this.tick()}},{key:"onBufferCreated",value:function(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use ".concat(i,".buffered to schedule main fragment loading")),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=r.type===ae;if(n){if(this.fragContextChanged(r))return this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===yn&&(this.state=hn));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Oe(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}var s=this.media;s&&(!this._hasEnoughToStart&&jr.getBuffered(s).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"onError",value:function(e,t){var r;if(t.fatal)this.state=kn;else switch(t.details){case Z.FRAG_GAP:case Z.FRAG_PARSING_ERROR:case Z.FRAG_DECRYPT_ERROR:case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ae,t);break;case Z.LEVEL_LOAD_ERROR:case Z.LEVEL_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Sn||(null==(r=t.context)?void 0:r.type)!==re||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Z.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 Z.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=hn,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==De||!this.altAudio){var i=(r===Ce?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r,ae),this.tick())}}},{key:"onLevelsUpdated",value:function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"seekToStartPos",value:function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to ".concat(r,", already seeking at ").concat(t));var i=this.timelineOffset;i&&r&&(r+=i);var n=this.getLevelDetails(),a=jr.getBuffered(e),s=a.length?a.start(0):0,o=s-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log("adjusting start position by ".concat(o," to match buffer start")),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position ".concat(r," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=r)}}}},{key:"_getAudioCodec",value:function(e){var 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}},{key:"_loadBitrateTestFrag",value:function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var i=r.hls,n=null==e?void 0:e.frag;if(n&&!r.fragContextChanged(n)){t.fragmentError=0,r.state=hn,r.startFragRequested=!1,r.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(ee.FRAG_LOADED,e),n.bitrateTest=!1}}).catch(function(t){r.state!==dn&&r.state!==kn&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,r=this.hls,i=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=i.video,c=i.text,d=i.id3,h=i.initSegment,f=l.details,v=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=mn,h){var g=h.tracks;if(g){var p=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,p,n),r.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:t,tracks:g})}var m=h.initPTS,y=h.timescale,E=this.initPTS[s.cc];if(X(m)&&(!E||E.baseTime!==m||E.timescale!==y)){var k=h.trackId;this.initPTS[s.cc]={baseTime:m,timescale:y,trackId:k},r.trigger(ee.INIT_PTS_FOUND,{frag:s,id:t,initPTS:m,timescale:y,trackId:k})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var T=f.fragments[s.sn-1-f.startSN],S=s.sn===f.startSN,b=!T||s.cc>T.cc;if(!1!==i.independent){var A=u.startPTS,L=u.endPTS,I=u.startDTS,R=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:A,endPTS:L,startDTS:I,endDTS:R};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),P=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,x=u.firstKeyFramePTS?u.firstKeyFramePTS:A;if(!S&&P<x-this.config.maxBufferHole&&!b)return void this.backtrack(s);b&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,L,s.start,R,!0)}else S&&A-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,A,L,I,R),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,S||b)}else{if(!S&&!b)return void this.backtrack(s);s.gap=!0}}if(v){var D=v.startPTS,C=v.endPTS,_=v.startDTS,M=v.endDTS;o&&(o.elementaryStreams[De]={startPTS:D,endPTS:C,startDTS:_,endDTS:M}),s.setElementaryStreamInfo(De,D,C,_,M),this.bufferFragmentData(v,s,o,n)}if(f&&null!=d&&d.samples.length){var O={id:t,frag:s,details:f,samples:d.samples};r.trigger(ee.FRAG_PARSING_METADATA,O)}if(f&&c){var F={id:t,frag:s,details:f,samples:c.samples};r.trigger(ee.FRAG_PARSING_USERDATA,F)}}}else this.resetWhenMissingContext(n)}},{key:"logMuxedErr",value:function(e){this.warn("".concat(Oe(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}},{key:"_bufferInitSegment",value:function(e,t,r,i){var n=this;if(this.state===mn){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=St(a.codec,l);"mp4a"===u&&(u="mp4a.40.5");var c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=a.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&-1===c.indexOf("firefox")&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&-1!==c.indexOf("android")&&"audio/mpeg"!==a.container&&(u="mp4a.40.2",this.log("Android: force audio codec to ".concat(u))),l&&l!==u&&this.log('Swapping manifest audio codec "'.concat(l,'" for "').concat(u,'"')),a.levelCodec=u,a.id=ae,this.log("Init audio buffer, container:".concat(a.container,", codecs[selected/level/parsed]=[").concat(u||"","/").concat(l||"","/").concat(a.codec,"]")),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=ae;var h=s.codec;if(4===(null==h?void 0:h.length))switch(h){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:".concat(s.container,", codecs[level/parsed]=[").concat(e.videoCodec||"","/").concat(h,"]").concat(s.codec!==h?" parsed-corrected="+s.codec:"").concat(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:".concat(o.container,", codecs[level/parsed]=[").concat(e.codecs,"/").concat(o.codec,"]")),delete t.video,delete t.audio);var f=Object.keys(t);if(f.length){if(this.hls.trigger(ee.BUFFER_CODECS,t),!this.hls)return;f.forEach(function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(ee.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}}},{key:"getMainFwdBufferInfo",value:function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ae)}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"backtrack",value:function(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=hn}},{key:"checkFragmentChanged",value:function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(jr.isBuffered(e,r)?t=this.getAppendedFrag(r):jr.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,n=t.level;i&&t.sn===i.sn&&i.level===n||(this.fragPlaying=t,this.hls.trigger(ee.FRAG_CHANGED,{frag:t}),i&&i.level===n||this.hls.trigger(ee.LEVEL_SWITCHED,{level:n}))}}}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return X(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(X(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?er(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(bn),hu=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["key-loader",r])).config=void 0,i.keyIdToKeyInfo={},i.emeController=null,i.config=e,i}return d(t,e),o(t,[{key:"abort",value:function(e){for(var t in this.keyIdToKeyInfo){var r=this.keyIdToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}}},{key:"detach",value:function(){for(var e in this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}},{key:"destroy",value:function(){for(var e in this.detach(),this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}},{key:"createKeyLoadError",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.KEY_LOAD_ERROR,r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;return new Gr({type:J.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i})}},{key:"loadClear",value:function(e,t,r){var i=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(var n,a=function(){var n=t[s];if(e.cc<=n.cc&&(!Oe(e)||!Oe(n)||e.sn<n.sn)||!r&&s==o-1)return{v:i.emeController.selectKeySystemFormat(n).then(function(e){if(i.emeController){n.setKeyFormat(e);var t=mi(e);return t?i.emeController.getKeySystemAccess([t]):void 0}})}},s=0,o=t.length;s<o;s++)if(n=a())return n.v;if(this.config.requireKeySystemAccessOnStart){var l=Ei(this.config);if(l.length)return this.emeController.getKeySystemAccess(l)}}return null}},{key:"load",value:function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(function(r){return t.loadInternal(e,r)}):this.loadInternal(e)}},{key:"loadInternal",value:function(e,t){var r,i;t&&e.setKeyFormat(t);var n=e.decryptdata;if(!n){var a=new Error(t?"Expected frag.decryptdata to be defined after setting format ".concat(t):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,a))}var s=n.uri;if(!s)return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(s,'"'))));var o=fu(n),l=this.keyIdToKeyInfo[o];if(null!=(r=l)&&r.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(i=l)&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(function(t){var r=t.keyInfo;return n.key=r.decryptdata.key,{frag:e,keyInfo:r}})}switch(this.log("".concat(this.keyIdToKeyInfo[o]?"Rel":"L","oading").concat(n.keyId?" keyId: "+Ae(n.keyId):""," URI: ").concat(n.uri," from ").concat(e.type," ").concat(e.level)),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(n.method,'"'))))}}},{key:"loadKeyEME",value:function(e,t){var r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){var n=function(e){var t=[];return tt(e,function(e){return t.push(e.subarray(8,24))}),t}(t.initSegment.data);if(n.length){var a=n[0];a.some(function(e){return 0!==e})&&(this.log("Using keyId found in init segment ".concat(Ae(a))),e.decryptdata.keyId=a,Ai.setKeyIdForUri(e.decryptdata.uri,a))}}var s=this.emeController.loadKey(r);return(e.keyLoadPromise=s.then(function(t){return e.mediaKeySessionContext=t,r})).catch(function(r){throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(r)}},{key:"loadKeyHTTP",value:function(e,t){var r=this,i=this.config,n=new(0,i.loader)(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise(function(a,s){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:function(e,t,i,n){var o=i.frag,l=i.keyInfo,u=fu(l.decryptdata);if(!o.decryptdata||l!==r.keyIdToKeyInfo[u])return s(r.createKeyLoadError(o,Z.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,a({frag:o,keyInfo:l})},onError:function(e,i,n,a){r.resetLoader(i),s(r.createKeyLoadError(t,Z.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(e.code," loading key ").concat(e.text)),n,fe({url:o.url,data:void 0},e)))},onTimeout:function(e,i,n){r.resetLoader(i),s(r.createKeyLoadError(t,Z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:function(e,i,n){r.resetLoader(i),s(r.createKeyLoadError(t,Z.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(o,u,c)})}},{key:"resetLoader",value:function(e){var t=e.frag,r=e.keyInfo,i=e.url,n=r.loader;t.keyLoader===n&&(t.keyLoader=null,r.loader=null);var a=fu(r.decryptdata)||i;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}])}(ve);function fu(e){if(e.keyFormat!==vi){var t=e.keyId;if(t)return Ae(t)}return e.uri}function vu(e){switch(e.type){case ie:return se;case ne:return oe;default:return ae}}function gu(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var pu=function(){return o(function e(t){a(this,e),this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()},[{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.destroyInternalLoaders()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"createInternalLoader",value:function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n}},{key:"getInternalLoader",value:function(e){return this.loaders[e.type]}},{key:"resetInternalLoader",value:function(e){this.loaders[e]&&delete this.loaders[e]}},{key:"destroyInternalLoaders",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}},{key:"destroy",value:function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}},{key:"onManifestLoading",value:function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te,url:r,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var r=t.id,i=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:re,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ie,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ne,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var r=this.loaders[re];if(r){var i=r.context;i&&!t.levels.some(function(e){return e===i.levelOrTrack})&&(r.abort(),delete this.loaders[re])}}},{key:"load",value:function(e){var t,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,l=s.context;if(l&&l.levelOrTrack===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives))return void(l.url===e.url?o.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):o.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(l.url)));o.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),s.abort()}if((r=e.type===te?a.manifestLoadPolicy.default:de({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),X(null==(t=e.deliveryDirectives)?void 0:t.part))&&(e.type===re&&null!==e.level?i=this.hls.levels[e.level].details:e.type===ie&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===ne&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,c=i.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);r=de({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var h=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),Di.isMediaPlaylist(s)||r.type!==te?n.handleTrackOrLevelPlaylist(e,t,r,i||null,a):n.handleMasterPlaylist(e,t,r,i)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,n=e.forceStartLoad;(r||n)&&(this.hls.logger.log("".concat(r?"auto":"force"," startLoad with configured startPosition ").concat(i)),this.hls.startLoad(i))}}},{key:"handleMasterPlaylist",value:function(e,t,r,i){var n=this,a=this.hls,s=e.data,o=gu(e,r),l=Di.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,i,t);var u=l.contentSteering,c=l.levels,d=l.sessionData,h=l.sessionKeys,f=l.startTimeOffset,v=l.variableList;this.variableList=v,c.forEach(function(e){var t=e.unknownCodecs;if(t)for(var r=n.hls.config.preferManagedMediaSource,i=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];vt(o,"audio",r)?(e.audioCodec=i=i?"".concat(i,",").concat(o):o,ht.audio[i.substring(0,4)]=2,t.splice(s,1)):vt(o,"video",r)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,ht.video[a.substring(0,4)]=2,t.splice(s,1))}});var g=Di.parseMasterPlaylistMedia(s,o,l),p=g.AUDIO,m=void 0===p?[]:p,y=g.SUBTITLES,E=g["CLOSED-CAPTIONS"];m.length&&(m.some(function(e){return!e.url})||!c[0].audioCodec||c[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Jr({}),bitrate:0,url:""})));a.trigger(ee.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:y,captions:E,contentSteering:u,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:v})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=gu(e,r),c=X(o)?o:X(s)?s:0,d=vu(r),h=Di.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===te){var f={attrs:new Jr({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Xi(h,0),a.trigger(ee.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,i,n)}},{key:"handleManifestParsingError",value:function(e,t,r,i,n){this.hls.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.MANIFEST_PARSING_ERROR,fatal:t.type===te,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})}},{key:"handleNetworkError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,a="A network ".concat(r?"timeout":"error"+(i?" (status "+i.code+")":"")," occurred while loading ").concat(e.type);e.type===re?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==ie&&e.type!==ne||(a+=" id: ".concat(e.id,' group-id: "').concat(e.groupId,'"'));var s=new Error(a);this.hls.logger.warn("[playlist-loader]: ".concat(a));var o=Z.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case te:o=r?Z.MANIFEST_LOAD_TIMEOUT:Z.MANIFEST_LOAD_ERROR,l=!0;break;case re:o=r?Z.LEVEL_LOAD_TIMEOUT:Z.LEVEL_LOAD_ERROR,l=!1;break;case ie:o=r?Z.AUDIO_TRACK_LOAD_TIMEOUT:Z.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ne:o=r?Z.SUBTITLE_TRACK_LOAD_TIMEOUT:Z.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:J.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:n};if(i){var d=(null==t?void 0:t.url)||e.url;c.response=fe({url:d,data:void 0},i)}this.hls.trigger(ee.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.levelOrTrack,c=i.id,d=i.groupId,h=i.deliveryDirectives,f=gu(t,i),v=vu(i),g="number"==typeof i.level&&v===ae?l:void 0,p=e.playlistParsingError;if(p){if(this.hls.logger.warn("".concat(p," ").concat(e.url)),!s.config.ignorePlaylistParsingErrors)return void s.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case te:case re:if(g)if(u){if(u!==s.levels[g]){var m=s.levels.indexOf(u);m>-1&&(g=m)}}else g=0;s.trigger(ee.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:r,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:o===te});break;case ie:s.trigger(ee.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h});break;case ne:s.trigger(ee.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r})}}}])}(),mu=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,e),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Pn,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;var r=this.logger=function(e,t,r){var i=me();if("object"===("undefined"==typeof console?"undefined":S(console))&&!0===e||"object"===S(e)){var n=["debug","log","info","warn","error"];n.forEach(function(t){i[t]=ye(t,e,r)});try{i.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.6.14"))}catch(e){return me()}n.forEach(function(t){Ee[t]=ye(t,e)})}else de(Ee,i);return i}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(e,t,r){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"');var i=Ql(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(function(e){var a="".concat("level"===e?"playlist":e,"LoadPolicy"),s=void 0===t[a],o=[];n.forEach(function(r){var n="".concat(e,"Loading").concat(r),l=t[n];if(void 0!==l&&s){o.push(n);var u=i[a].default;switch(t[a]={default:u},r){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn('hls.js config: "'.concat(o.join('", "'),'" setting(s) are deprecated, use "').concat(a,'": ').concat(Kt(t[a])))}),fe(fe({},i),t)}(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&$l(i,r);var n=i.abrController,s=i.bufferController,o=i.capLevelController,l=i.errorController,u=i.fpsController,c=new l(this),d=this.abrController=new n(this),h=new Ir(this),f=i.interstitialsController,v=f?this.interstitialsController=new f(this,e):null,g=this.bufferController=new s(this,h),p=this.capLevelController=new o(this),m=new u(this),y=new pu(this),E=i.contentSteeringController,k=E?new E(this):null,T=this.levelController=new ou(this,k),b=new au(this),A=new hu(this.config,this.logger),L=this.streamController=new du(this,h,A),I=this.gapController=new Jl(this,h);p.setStreamController(L),m.setStreamController(L);var R=[y,T,L];v&&R.splice(1,0,v),k&&R.splice(1,0,k),this.networkControllers=R;var w=[d,g,I,p,m,b,h];this.audioTrackController=this.createController(i.audioTrackController,R);var P=i.audioStreamController;P&&R.push(this.audioStreamController=new P(this,h,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);var x=i.subtitleStreamController;x&&R.push(this.subtititleStreamController=new x(this,h,A)),this.createController(i.timelineController,w),A.emeController=this.emeController=this.createController(i.emeController,w),this.cmcdController=this.createController(i.cmcdController,w),this.latencyController=this.createController(su,w),this.coreComponents=w,R.push(c);var D=c.onErrorOut;"function"==typeof D&&this.on(ee.ERROR,D,c),this.on(ee.MANIFEST_LOADED,y.onManifestLoaded,y)}return o(e,[{key:"createController",value:function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,r)}},{key:"once",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,r)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,i=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,r,i)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,r){return this._emitter.emit(e,t,r)}},{key:"trigger",value:function(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;var r=e===ee.ERROR;this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1}},{key:"listenerCount",value:function(e){return this._emitter.listenerCount(e)}},{key:"destroy",value:function(){this.logger.log("destroy"),this.trigger(ee.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(function(e){return e.destroy()}),this.networkControllers.length=0,this.coreComponents.forEach(function(e){return e.destroy()}),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}},{key:"attachMedia",value:function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument (".concat(e,")"));this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(ee.MEDIA_ATTACHING,n)}}},{key:"detachMedia",value:function(){this.logger.log("detachMedia"),this.trigger(ee.MEDIA_DETACHING,{}),this._media=null}},{key:"transferMedia",value:function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(ee.MEDIA_DETACHING,{transferMedia:e}),e}},{key:"loadSource",value:function(e){this.stopLoad();var t=this.media,r=this._url,i=this._url=Pe.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(i)),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(ee.MANIFEST_LOADING,{url:e})}},{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,t=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}},{key:"stopLoad",value:function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"resumeBuffering",value:function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(function(e){e.resumeBuffering&&e.resumeBuffering()}))}},{key:"pauseBuffering",value:function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(function(e){e.pauseBuffering&&e.pauseBuffering()}))}},{key:"inFlightFragments",get:function(){var e=l({},ae,this.streamController.inFlightFrag);return this.audioStreamController&&(e[se]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[oe]=this.subtititleStreamController.inFlightFrag),e}},{key:"swapAudioCodec",value:function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}},{key:"removeLevel",value:function(e){this.levelController.removeLevel(e)}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})}}}()),e}},{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:".concat(e)),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:".concat(e)),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:".concat(e)),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:".concat(e)),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return _t.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"setAudioOption",value:function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}},{key:"setSubtitleOption",value:function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(e){this.latencyController.targetLatency=e}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}},{key:"getMediaDecodingInfo",value:function(e){return xt(e,Yt(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return xn}},{key:"isMSESupported",value:function(){return cu()}},{key:"isSupported",value:function(){return function(){if(!cu())return!1;var e=Te();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(function(t){return e.isTypeSupported(pt(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(pt(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return Te()}},{key:"Events",get:function(){return ee}},{key:"MetadataSchema",get:function(){return Zn}},{key:"ErrorTypes",get:function(){return J}},{key:"ErrorDetails",get:function(){return Z}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:Xl},set:function(t){e.defaultConfig=t}}])}();mu.defaultConfig=void 0;var yu=[".mp4",".webm",".ogg",".m3u8",".ts"],Eu=[".flv",".f4v",".swf",".wmv",".avi",".mov",".mkv"];function ku(e){try{var t=new URL(e,"http://dummy").pathname;return-1===(r=t.lastIndexOf("."))?"":t.slice(r).toLowerCase()}catch(t){var r;return-1===(r=e.lastIndexOf("."))?"":(e.slice(r).split(/[?#]/)[0]||"").toLowerCase()}}function Tu(e){var t=ku(e);return-1!==Eu.indexOf(t)}function Su(e,t){var r,i,n,a=t.licenseKey,s=t.debug,o=void 0!==s&&s,l=!1,u=!1,c=Math.max(0,Math.min(1,e.volume||1)),d=new Map,h=!1,f={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function v(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];o&&console.log.apply(console,M(["[AdStormPlayer]"],_(e),!1))}function g(e,t){var r,i,n=d.get(e);if(n)try{for(var a=C(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("[AdStormPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function p(e){e&&0!==e.length&&e.forEach(function(e){try{new Image(1,1).src=e,v("Fired tracking pixel:",e)}catch(e){console.warn("[AdStormPlayer] Error firing tracking pixel:",e)}})}function m(e){var t=[];try{var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.querySelector("parsererror");if(i)return console.error("[AdStormPlayer] XML parsing error:",i.textContent),[];r.querySelectorAll("Ad").forEach(function(e){var r,i,n,a,s=e.getAttribute("id")||"unknown",o=(null===(r=e.querySelector("AdTitle"))||void 0===r?void 0:r.textContent)||"Ad",l=((null===(i=e.querySelector("Duration"))||void 0===i?void 0:i.textContent)||"00:00:30").split(":"),u=3600*parseInt(l[0]||"0",10)+60*parseInt(l[1]||"0",10)+parseFloat(l[2]||"0"),c=e.querySelectorAll("MediaFile"),d=[];if(c.forEach(function(e){var t,r=e.getAttribute("type")||"",i=(null===(t=e.textContent)||void 0===t?void 0:t.trim())||"",n=parseInt(e.getAttribute("width")||"1920",10),a=parseInt(e.getAttribute("height")||"1080",10),s=e.getAttribute("bitrate")?parseInt(e.getAttribute("bitrate"),10):void 0;if(i){var o=i;if((i=function(e){return".flv"===ku(e)?e.replace(/\.flv(\?|$)/i,".mp4$1"):e}(i))!==o&&v("Converted FLV to MP4: ".concat(o," -> ").concat(i)),Tu(i)){var l=ku(i);v("Skipping unsupported format: ".concat(i," (extension: ").concat(l,", declared type: ").concat(r,")"))}else!function(e,t){if(Tu(e))return!1;var r=ku(e);return-1!==yu.indexOf(r)||(""===r||"."===r)&&(t.includes("video/mp4")||t.includes("video/webm")||t.includes("m3u8")||t.includes("application/x-mpegurl"))}(i,r)?v("Skipping incompatible media file: ".concat(i," (type: ").concat(r,")")):(d.push({url:i,type:r,width:n,height:a,bitrate:s}),v("Found media file: ".concat(i," (").concat(r,", ").concat(n,"x").concat(a,")")))}else v("Skipping empty MediaFile URL")}),0!==d.length){var h={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],error:[]};e.querySelectorAll("Impression").forEach(function(e){var t,r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&h.impression.push(r)}),e.querySelectorAll("Tracking").forEach(function(e){var t,r=e.getAttribute("event"),i=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(r&&i){var n=r;h[n]&&h[n].push(i)}});var f=null===(a=null===(n=e.querySelector("ClickThrough"))||void 0===n?void 0:n.textContent)||void 0===a?void 0:a.trim();t.push({id:s,title:o,duration:u,mediaFiles:d,trackingUrls:h,clickThrough:f}),v("Parsed ad: ".concat(o,", duration: ").concat(u,"s, media files: ").concat(d.length))}else v("No valid media files found in ad:",s)})}catch(e){console.error("[AdStormPlayer] Error parsing VAST XML:",e)}return t}function y(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function E(){if(r&&n){var t=n;r.addEventListener("timeupdate",function(){if(t&&r){var e=r.currentTime/t.duration;e>=.25&&!f.firstQuartile&&(f.firstQuartile=!0,p(t.trackingUrls.firstQuartile)),e>=.5&&!f.midpoint&&(f.midpoint=!0,p(t.trackingUrls.midpoint)),e>=.75&&!f.thirdQuartile&&(f.thirdQuartile=!0,p(t.trackingUrls.thirdQuartile))}}),r.addEventListener("playing",function(){t&&!f.start&&(f.start=!0,p(t.trackingUrls.start),v("Ad started playing"))}),r.addEventListener("ended",function(){t&&!f.complete&&(f.complete=!0,p(t.trackingUrls.complete),v("Ad completed"),function(){v("Handling ad completion"),l=!1,y(!1),i&&(i.style.opacity="0",setTimeout(function(){i&&(i.style.display="none",i.style.pointerEvents="none")},300));e.style.visibility="visible",e.style.opacity="1",e.muted=u,e.volume=c,g("content_resume"),g("all_ads_completed")}())}),r.addEventListener("error",function(e){console.error("[AdStormPlayer] Ad video error:",e),t&&p(t.trackingUrls.error),k()})}}function k(){v("Handling ad error"),l=!1,y(!1),e.muted=u,e.volume=c,e.style.visibility="visible",e.style.opacity="1",i&&(i.style.display="none",i.style.pointerEvents="none"),g("ad_error")}function T(t){return x(this,void 0,void 0,function(){var r,i,n;return D(this,function(s){switch(s.label){case 0:return r=function(t,r){var i="https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(a,"/pod"),n={video:{codec:"h264",width:e.videoWidth||1280,height:e.videoHeight||720,fps:29.97,bitrate:5e3,profile:"high",pix_fmt:"yuv420p",has_b_frames:0},audio:{codec:"aac",sample_rate:48e3,bitrate:128}},s=r||n,o=encodeURIComponent(JSON.stringify(s));return"".concat(i,"?duration=").concat(Math.ceil(t),"&metadata=").concat(o)}(t),v("Fetching VAST from:",r),[4,fetch(r,{headers:{Accept:"application/xml"}})];case 1:if(!(i=s.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(i.status," ").concat(i.statusText));return[4,i.text()];case 2:return v("VAST response received, length:",(n=s.sent()).length),[2,m(n)]}})})}return{initialize:function(){var t;if(v("Initializing"),!i){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",r.style.transition="opacity 0.3s ease-in-out",r.style.opacity="0",null===(t=e.parentElement)||void 0===t||t.appendChild(r),i=r}},requestAds:function(e){return x(this,void 0,void 0,function(){var t,r,i,a;return D(this,function(s){switch(s.label){case 0:if(v("Requesting ads for duration:",e),l)return[2,Promise.reject(new Error("Ad already playing"))];s.label=1;case 1:return s.trys.push([1,3,,4]),t=30,r=parseInt(e,10),!isNaN(r)&&r>0&&(t=r),[4,T(t)];case 2:return 0===(i=s.sent()).length?(v("No ads available from VAST response"),g("ad_error"),[2,Promise.resolve()]):(n=i[0],v("Ad loaded: ".concat(n.title,", duration: ").concat(n.duration,"s")),p(n.trackingUrls.impression),f.impression=!0,[2,Promise.resolve()]);case 3:return a=s.sent(),console.error("[AdStormPlayer] Error requesting ads:",a),g("ad_error"),[2,Promise.reject(a)];case 4:return[2]}})})},play:function(){return x(this,void 0,void 0,function(){var t,a;return D(this,function(s){switch(s.label){case 0:if(!n)return[2,Promise.reject(new Error("No ad loaded"))];v("Starting ad playback"),s.label=1;case 1:if(s.trys.push([1,3,,4]),r||((o=document.createElement("video")).style.position="absolute",o.style.left="0",o.style.top="0",o.style.width="100%",o.style.height="100%",o.style.objectFit="contain",o.style.backgroundColor="#000",o.style.zIndex="15",o.playsInline=!0,o.muted=!1,o.volume=u?0:c,r=o,null==i||i.appendChild(r),E()),f={impression:f.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",setTimeout(function(){e.style.visibility="hidden"},300),e.muted=!0,e.volume=0,h&&e.pause(),l=!0,y(!0),r&&(r.volume=u?0:c,r.muted=u),i&&(i.style.display="flex",i.style.pointerEvents="auto",i.offsetHeight,i.style.opacity="1"),g("content_pause"),!(t=function(t){if(0===t.length)return null;if(1===t.length)return t[0];var r=t.filter(function(e){return e.type.includes("video/mp4")}),i=r.length>0?r:t,n=e.videoWidth||1280,a=e.videoHeight||720;return i.sort(function(e,t){return Math.abs(e.width-n)+Math.abs(e.height-a)-(Math.abs(t.width-n)+Math.abs(t.height-a))}),i[0]||null}(n.mediaFiles)))throw new Error("No media file available");return v("Playing media file:",t.url),r.src=t.url,[4,r.play()];case 2:return s.sent(),[2,Promise.resolve()];case 3:return a=s.sent(),console.error("[AdStormPlayer] Error playing ad:",a),k(),[2,Promise.reject(a)];case 4:return[2]}var o})})},stop:function(){return x(this,void 0,void 0,function(){return D(this,function(t){return v("Stopping ad"),l=!1,y(!1),i&&(i.style.opacity="0",setTimeout(function(){i&&(i.style.display="none",i.style.pointerEvents="none")},300)),r&&(r.pause(),r.src=""),e.style.visibility="visible",e.style.opacity="1",n=void 0,[2]})})},destroy:function(){v("Destroying"),l=!1,y(!1),e.muted=u,e.volume=c,e.style.visibility="visible",e.style.opacity="1",r&&(r.pause(),r.src="",r.remove(),r=void 0),(null==i?void 0:i.parentElement)&&i.parentElement.removeChild(i),i=void 0,n=void 0,d.clear()},isAdPlaying:function(){return l},resize:function(e,t){v("Resizing to ".concat(e,"x").concat(t)),i&&(i.style.width="".concat(e,"px"),i.style.height="".concat(t,"px")),r&&(r.style.width="".concat(e,"px"),r.style.height="".concat(t,"px"))},on:function(e,t){d.has(e)||d.set(e,new Set),d.get(e).add(t)},off:function(e,t){var r;null===(r=d.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?c:Math.max(0,Math.min(1,t));v("updateOriginalMutedState: muted=".concat(e,", volume=").concat(r)),u=e,c=r},getOriginalMutedState:function(){return u},getOriginalVolume:function(){return c},setAdVolume:function(e){r&&l&&(r.volume=Math.max(0,Math.min(1,e)),r.muted=0===e)},getAdVolume:function(){return r&&l?r.volume:1},showPlaceholder:function(){var t;if(!i){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),i=r}i&&(i.style.display="flex",i.style.opacity="1",i.style.pointerEvents="auto")},hidePlaceholder:function(){i&&(i.style.opacity="0",setTimeout(function(){i&&(i.style.display="none",i.style.pointerEvents="none")},300))},setAllowNativeHls:function(e){h=e,v("allowNativeHls set to: ".concat(e))}}}function bu(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=0;n<t.length;n++){var a=t[n];if(null!=a)for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(i[s]=a[s])}return i}),Array.from||(Array.from=function(e,t,r){var i=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var n=i.length>>>0,a=new Array(n),s=0;s<n;s++)a[s]=t?t.call(r,i[s],s):i[s];return a}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){var e=function(){function e(t){var r=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){r.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,r=e.startsWith("?")?e.slice(1):e;r&&r.split("&").forEach(function(e){var r=_(e.split("="),2),i=r[0],n=r[1];if(i){var a=t.safeDecodeURIComponent(i),s=n?t.safeDecodeURIComponent(n):"";t.append(a,s)}})},e.prototype.safeDecodeURIComponent=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},e.prototype.append=function(e,t){var r=this.params.get(e)||[];r.push(String(t)),this.params.set(e,r)},e.prototype.delete=function(e){this.params.delete(e)},e.prototype.get=function(e){var t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null},e.prototype.getAll=function(e){return this.params.get(e)||[]},e.prototype.has=function(e){return this.params.has(e)},e.prototype.set=function(e,t){this.params.set(e,[String(t)])},e.prototype.forEach=function(e){var t=this;this.params.forEach(function(r,i){r.forEach(function(r){e(r,i,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,r){t.forEach(function(t){e.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(t)))})}),e.join("&")},e}();window.URLSearchParams=e}}(),function(){if("undefined"==typeof TextEncoder){var e=function(){function e(){this.encoding="utf-8"}return e.prototype.encode=function(e){for(var t=[],r=0;r<e.length;r++){var i=e.charCodeAt(r);i<128?t.push(i):i<2048?t.push(192|i>>6,128|63&i):i<55296||i>=57344?t.push(224|i>>12,128|i>>6&63,128|63&i):(r++,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i))}return new Uint8Array(t)},e}();window.TextEncoder=e}}(),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){var t=this.constructor;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})})}function Au(){var e=navigator.userAgent,t=function(){var e;if("userAgentData"in navigator&&(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform))return navigator.userAgentData.platform;var t=navigator.userAgent;return/Mac|iPhone|iPad|iPod/i.test(t)?/iPhone|iPad|iPod/i.test(t)?"iPhone":"MacIntel":/Win/i.test(t)?"Win32":/Linux/i.test(t)?/Android/i.test(t)?"Linux armv8l":"Linux x86_64":/CrOS/i.test(t)?"CrOS":navigator.platform||"Unknown"}(),r="Unknown",i="0",n=0,a=!1,s=!1,o=!0;if(/Web0S|webOS/i.test(e))r="LG WebOS",a=!0,"Unknown"!==(i=(l=e.match(/Web0S[/\s]*([\d.]+)/i))&&l[1]?l[1]:"Unknown")&&(n=(u=i.split("."))[0]?parseInt(u[0],10):0);else if(/Tizen/i.test(e)){var l,u;if(r="Samsung Tizen",a=!0,"Unknown"!==(i=(l=e.match(/Tizen[/\s]*([\d.]+)/i))&&l[1]?l[1]:"Unknown"))n=(u=i.split("."))[0]?parseInt(u[0],10):0}else/SMART-TV|SmartTV/i.test(e)?(r="Smart TV",a=!0):/NetCast/i.test(e)?(r="LG NetCast",a=!0,s=!0):/BRAVIA/i.test(e)&&(r="Sony BRAVIA",a=!0);var c=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e),d=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e);return c>0&&(a||(r="Chrome",i=c.toString(),n=c),c<50&&(o=!1,s=!0)),d>0&&d<600&&(o=!1,a&&(s=!0)),"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(o=!1),"undefined"==typeof URLSearchParams&&(o=!1),{name:r,version:i,majorVersion:n,isSmartTV:a,isLegacyTV:s,platform:t,supportsModernJS:o}}function Lu(e){if(void 0===e&&(e=!1),e){var t=Au();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",{browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsModernJS:t.supportsModernJS,userAgent:navigator.userAgent})}}function Iu(){var e={};return Au().isSmartTV&&(e.allowNativeHls=!0),e}var Ru=function(){function e(e){var t;this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,bu();var r=Iu();this.config=w(w({},e),r),this.video=e.videoElement,Lu(e.debugAdTiming),this.config.licenseKey||console.warn("[StormcloudVideoPlayer] No license key provided - ads will not work"),this.adPlayer=Su(this.video,{licenseKey:this.config.licenseKey||"",debug:null!==(t=this.config.debugAdTiming)&&void 0!==t&&t})}return e.prototype.load=function(){return x(this,void 0,void 0,function(){var e,t,r=this;return D(this,function(i){switch(i.label){case 0:return this.attached||this.attach(),this.shouldUseNativeHls()?(this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(e=this.config.lowLatencyMode)&&void 0!==e&&e,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using native HLS playback:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls}),this.adPlayer.initialize(),this.adPlayer.setAllowNativeHls(!!this.config.allowNativeHls),this.config.autoplay?[4,null===(t=this.video.play())||void 0===t?void 0:t.catch(function(){})]:[3,2]):[3,3];case 1:i.sent(),i.label=2;case 2:return[2];case 3:return this.hls=new mu(w(w({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:this.config.lowLatencyMode?1.5:1},this.config.lowLatencyMode?{liveSyncDuration:2}:{}),{maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:.5,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,startPosition:-1})),this.hls.on(mu.Events.MEDIA_ATTACHED,function(){var e;null===(e=r.hls)||void 0===e||e.loadSource(r.config.src)}),this.hls.on(mu.Events.MANIFEST_PARSED,function(){return x(r,void 0,void 0,function(){var e,t,r,i,n,a;return D(this,function(s){switch(s.label){case 0:return this.isLiveStream=null!==(i=null===(r=null===(t=this.hls)||void 0===t?void 0:t.levels)||void 0===r?void 0:r.some(function(e){var t,r;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(r=null==e?void 0:e.details)||void 0===r?void 0:r.type)}))&&void 0!==i&&i,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream}),this.adPlayer.initialize(),this.adPlayer.setAllowNativeHls(!!this.config.allowNativeHls),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,e=null!==(n=this.config.minSegmentsBeforePlay)&&void 0!==n?n:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",e,"segments to buffer before playback"),0!==e&&this.config.autoplay?[3,2]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(a=this.video.play())||void 0===a?void 0:a.catch(function(){})]:[3,2]);case 1:s.sent(),s.label=2;case 2:return[2]}})})}),this.hls.on(mu.Events.FRAG_BUFFERED,function(){return x(r,void 0,void 0,function(){var e,t,r,i=this;return D(this,function(n){switch(n.label){case 0:return this.hasInitialBufferCompleted?[2]:(this.bufferedSegmentsCount++,e=null!==(t=this.config.minSegmentsBeforePlay)&&void 0!==t?t:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Buffered segment ".concat(this.bufferedSegmentsCount,"/").concat(e)),this.bufferedSegmentsCount>=e?(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete. Starting playback."),[4,null===(r=this.video.play())||void 0===r?void 0:r.catch(function(e){i.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})]):[3,2]):[3,2]);case 1:n.sent(),n.label=2;case 2:return[2]}})})}),this.hls.on(mu.Events.FRAG_PARSING_METADATA,function(e,t){((null==t?void 0:t.samples)||[]).map(function(e){return{key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts}}).forEach(function(e){return r.onId3Tag(e)})}),this.hls.on(mu.Events.FRAG_CHANGED,function(e,t){var i,n,a,s,o,l,u=null==t?void 0:t.frag,c=null==u?void 0:u.tagList;if(Array.isArray(c))try{for(var d=C(c),h=d.next();!h.done;h=d.next()){var f=h.value,v="",g="";if(Array.isArray(f))v=String(null!==(a=f[0])&&void 0!==a?a:""),g=String(null!==(s=f[1])&&void 0!==s?s:"");else if("string"==typeof f){var p=f.indexOf(":");p>=0?(v=f.substring(0,p),g=f.substring(p+1)):(v=f,g="")}if(v)if(v.includes("EXT-X-CUE-OUT")){var m=r.parseCueOutDuration(g);r.onScte35Marker(w(w({type:"start"},void 0!==m?{durationSeconds:m}:{}),{raw:{tag:v,value:g}}))}else if(v.includes("EXT-X-CUE-OUT-CONT")){var y=r.parseCueOutCont(g);r.onScte35Marker(w(w(w({type:"progress"},void 0!==(null==y?void 0:y.duration)?{durationSeconds:y.duration}:{}),void 0!==(null==y?void 0:y.elapsed)?{ptsSeconds:y.elapsed}:{}),{raw:{tag:v,value:g}}))}else if(v.includes("EXT-X-CUE-IN"))r.onScte35Marker({type:"end",raw:{tag:v,value:g}});else if(v.includes("EXT-X-DATERANGE")){var E=r.parseAttributeList(g),k="SCTE35-OUT"in E,T="SCTE35-IN"in E,S=String(null!==(o=E.CLASS)&&void 0!==o?o:""),b=null!==(l=r.toNumber(E.DURATION))&&void 0!==l?l:r.toNumber(E["PLANNED-DURATION"]);(k||/com\.apple\.hls\.cue/i.test(S))&&r.onScte35Marker(w(w({type:"start"},void 0!==b?{durationSeconds:b}:{}),{raw:{tag:v,value:g,attrs:E}})),T&&r.onScte35Marker({type:"end",raw:{tag:v,value:g,attrs:E}})}}}catch(e){i={error:e}}finally{try{h&&!h.done&&(n=d.return)&&n.call(d)}finally{if(i)throw i.error}}}),this.hls.on(mu.Events.ERROR,function(e,t){var i,n;if(null==t?void 0:t.fatal)switch(t.type){case mu.ErrorTypes.NETWORK_ERROR:null===(i=r.hls)||void 0===i||i.startLoad();break;case mu.ErrorTypes.MEDIA_ERROR:null===(n=r.hls)||void 0===n||n.recoverMediaError();break;default:r.destroy()}}),this.hls.attachMedia(this.video),[2]}})})},e.prototype.attach=function(){var e=this;this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.adPlayer.initialize(),this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.adPlayer.on("all_ads_completed",function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad completed - ending ad break"),e.inAdBreak&&e.handleAdPodComplete()}),this.adPlayer.on("ad_error",function(){console.error("[StormcloudVideoPlayer] Ad error occurred"),e.inAdBreak&&e.handleAdPodComplete()}),this.adPlayer.on("content_pause",function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Content paused for ad")}),this.adPlayer.on("content_resume",function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Content resuming after ad")}),this.timeUpdateHandler=function(){},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.nativeHlsMode&&e.videoSrcProtection&&!e.adPlayer.isAdPlaying()){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring");var t=e.video.currentTime,r=e.video.paused;e.video.src=e.videoSrcProtection,e.video.currentTime=t,r||e.video.play().catch(function(){})}},this.video.addEventListener("emptied",this.emptiedHandler))},e.prototype.shouldUseNativeHls=function(){if("other"===this.getStreamType())return!0;var e=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!e)},e.prototype.onId3Tag=function(e){"number"==typeof e.ptsSeconds&&this.updatePtsDrift(e.ptsSeconds);var t=this.parseScte35FromId3(e);t&&this.onScte35Marker(t)},e.prototype.parseScte35FromId3=function(e){var t,r,i=this.decodeId3ValueToText(e.value);if(i){var n=i.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||i.match(/CUE-OUT(?::([^\r\n]*))?/i);if(n){var a=(null!==(t=n[1])&&void 0!==t?t:"").trim(),s=this.parseCueOutDuration(a);return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==s?{durationSeconds:s}:{}),{raw:{id3:i}})}var o=i.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(o){a=(null!==(r=o[1])&&void 0!==r?r:"").trim();var l=this.parseCueOutCont(a);return w(w(w({type:"progress"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==(null==l?void 0:l.duration)?{durationSeconds:l.duration}:{}),{raw:{id3:i}})}return i.match(/EXT-X-CUE-IN\b/i)||i.match(/CUE-IN\b/i)?w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:i}}):void 0}},e.prototype.decodeId3ValueToText=function(e){try{if("string"==typeof e)return e;var t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;for(var r="",i=0;i<e.length;i++)r+=String.fromCharCode(e[i]);return r}catch(e){return}},e.prototype.onScte35Marker=function(e){return x(this,void 0,void 0,function(){var t;return D(this,function(r){switch(r.label){case 0:return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime}),"start"!==e.type?[3,2]:this.inAdBreak?[2]:(this.inAdBreak=!0,t=null!=e.durationSeconds?1e3*e.durationSeconds:3e4,this.expectedAdBreakDurationMs=t,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad break:",{durationMs:t,durationSeconds:e.durationSeconds}),this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),[4,this.handleAdStart(e)]);case 1:return r.sent(),null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs),[2];case 2:return"progress"===e.type&&this.inAdBreak?(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),[2]):"end"!==e.type?[3,5]:this.inAdBreak?(this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.clearAdStopTimer(),this.adPlayer.isAdPlaying()?[4,this.adPlayer.stop()]:[3,4]):[2];case 3:r.sent(),r.label=4;case 4:return this.handleAdPodComplete(),[2];case 5:return[2]}})})},e.prototype.handleAdStart=function(e){return x(this,void 0,void 0,function(){var t,r,i;return D(this,function(n){switch(n.label){case 0:t=null!==(i=e.durationSeconds)&&void 0!==i?i:30,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Requesting ads for duration:",t),n.label=1;case 1:return n.trys.push([1,4,,5]),[4,this.adPlayer.requestAds(String(t))];case 2:return n.sent(),[4,this.adPlayer.play()];case 3:return n.sent(),[3,5];case 4:return r=n.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Ad request/play failed:",r),this.handleAdPodComplete(),[3,5];case 5:return[2]}})})},e.prototype.parseCueOutDuration=function(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var r=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(r&&null!=r[1]){var i=parseFloat(r[1]);return Number.isNaN(i)?void 0:i}},e.prototype.parseCueOutCont=function(e){var t=e.match(/Elapsed\s*=\s*([0-9.]+)/i),r=e.match(/Duration\s*=\s*([0-9.]+)/i),i={};if(t&&null!=t[1]){var n=parseFloat(t[1]);Number.isNaN(n)||(i.elapsed=n)}if(r&&null!=r[1]){var a=parseFloat(r[1]);Number.isNaN(a)||(i.duration=a)}if("elapsed"in i||"duration"in i)return i},e.prototype.parseAttributeList=function(e){for(var t,r,i,n,a={},s=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(n=s.exec(e));){var o=null!==(t=n[1])&&void 0!==t?t:"",l=null!==(i=null!==(r=n[3])&&void 0!==r?r:n[4])&&void 0!==i?i:"";l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),o&&(a[o]=l)}return a},e.prototype.toNumber=function(e){if(null!=e){var t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}},e.prototype.scheduleAdStopCountdown=function(e){var t=this;this.clearAdStopTimer();var r=Math.max(0,Math.floor(e));0!==r?this.adStopTimerId=window.setTimeout(function(){t.handleAdPodComplete()},r):this.handleAdPodComplete()},e.prototype.clearAdStopTimer=function(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)},e.prototype.updatePtsDrift=function(e){var t=1e3*(this.video.currentTime-e);if(Number.isFinite(t)&&!(Math.abs(t)>6e4)){this.ptsDriftEmaMs=.9*this.ptsDriftEmaMs+.1*t}},e.prototype.handleAdPodComplete=function(){var e;this.clearAdStopTimer(),this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.adPlayer.stop().catch(function(){});var t=this.adPlayer.getOriginalMutedState(),r=this.adPlayer.getOriginalVolume();this.video.muted!==t&&(this.video.muted=t),Math.abs(this.video.volume-r)>.01&&(this.video.volume=r),this.video.paused&&(null===(e=this.video.play())||void 0===e||e.catch(function(){})),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad break complete")},e.prototype.isAdPlaying=function(){return this.inAdBreak&&this.adPlayer.isAdPlaying()},e.prototype.isShowingAds=function(){return this.adPlayer.isAdPlaying()},e.prototype.getStreamType=function(){var e=this.config.src.toLowerCase();return e.includes(".m3u8")||e.includes("/hls/")||e.includes("application/vnd.apple.mpegurl")?"hls":"other"},e.prototype.shouldShowNativeControls=function(){var e,t;return"other"===this.getStreamType()?!(null!==(e=this.config.showCustomControls)&&void 0!==e&&e):!(!this.config.allowNativeHls||null!==(t=this.config.showCustomControls)&&void 0!==t&&t)},e.prototype.toggleMute=function(){if(this.adPlayer.isAdPlaying()){var e=!this.video.muted;this.adPlayer.updateOriginalMutedState(e,this.video.volume),this.adPlayer.setAdVolume(e?0:1)}else this.video.muted=!this.video.muted,this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume)},e.prototype.toggleFullscreen=function(){var e=this;return new Promise(function(t,r){if(document.fullscreenElement)document.exitFullscreen().then(function(){return t()}).catch(r);else{var i=e.video.parentElement;if(!i)return void r(new Error("No parent container found for fullscreen"));i.requestFullscreen().then(function(){return t()}).catch(r)}})},e.prototype.isMuted=function(){return this.video.muted},e.prototype.setMuted=function(e){this.video.muted=e,this.adPlayer.updateOriginalMutedState(e,this.video.volume),this.adPlayer.isAdPlaying()&&this.adPlayer.setAdVolume(e?0:1)},e.prototype.setVolume=function(e){var t=Math.max(0,Math.min(1,e));this.adPlayer.isAdPlaying()?(this.adPlayer.setAdVolume(t),this.adPlayer.updateOriginalMutedState(0===t,t)):(this.video.volume=t,this.video.muted=0===t,this.adPlayer.updateOriginalMutedState(0===t,t))},e.prototype.isFullscreen=function(){return!!document.fullscreenElement},e.prototype.isLive=function(){return this.isLiveStream},Object.defineProperty(e.prototype,"videoElement",{get:function(){return this.video},enumerable:!1,configurable:!0}),e.prototype.resize=function(){if(this.adPlayer&&this.adPlayer.isAdPlaying()){var e=this.video.clientWidth||640,t=this.video.clientHeight||360;this.adPlayer.resize(e,t)}},e.prototype.destroy=function(){var e,t;this.clearAdStopTimer(),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.adPlayer)||void 0===t||t.destroy()},e.prototype.getCurrentAdIndex=function(){return 0},e.prototype.getTotalAdsInBreak=function(){return 1},e}(),wu={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Pu=z.createContext&&z.createContext(wu),xu=["attr","size","title"];function Du(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){if(t.indexOf(i)>=0)continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Cu(){return Cu=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Cu.apply(this,arguments)}function _u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Mu(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?_u(Object(r),!0).forEach(function(t){Ou(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_u(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Ou(e,t,r){var i;return i=function(e,t){if("object"!=S(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=S(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==S(i)?i:i+"")in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Fu(e){return e&&e.map(function(e,t){return z.createElement(e.tag,Mu({key:t},e.attr),Fu(e.child))})}function Nu(e){return function(t){return z.createElement(Uu,Cu({attr:Mu({},e.attr)},t),Fu(e.child))}}function Uu(e){var t=function(t){var r,i=e.attr,n=e.size,a=e.title,s=Du(e,xu),o=n||t.size||"1em";return t.className&&(r=t.className),e.className&&(r=(r?r+" ":"")+e.className),z.createElement("svg",Cu({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,i,s,{className:r,style:Mu(Mu({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),a&&z.createElement("title",null,a),e.children)};return void 0!==Pu?z.createElement(Pu.Consumer,null,function(e){return t(e)}):t(wu)}function Bu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function Gu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M0 180V56c0-13.3 10.7-24 24-24h124c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H64v84c0 6.6-5.4 12-12 12H12c-6.6 0-12-5.4-12-12zM288 44v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12V56c0-13.3-10.7-24-24-24H300c-6.6 0-12 5.4-12 12zm148 276h-40c-6.6 0-12 5.4-12 12v84h-84c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24V332c0-6.6-5.4-12-12-12zM160 468v-40c0-6.6-5.4-12-12-12H64v-84c0-6.6-5.4-12-12-12H12c-6.6 0-12 5.4-12 12v124c0 13.3 10.7 24 24 24h124c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function Hu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z"},child:[]}]})(e)}function Vu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z"},child:[]}]})(e)}function Ku(e){return Nu({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"},child:[]}]})(e)}function ju(e){return Nu({tag:"svg",attr:{viewBox:"0 0 384 512"},child:[{tag:"path",attr:{d:"M215.03 72.04L126.06 161H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V89.02c0-21.47-25.96-31.98-40.97-16.98zm123.2 108.08c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 229.28 336 242.62 336 257c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.87z"},child:[]}]})(e)}function Yu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zM461.64 256l45.64-45.64c6.3-6.3 6.3-16.52 0-22.82l-22.82-22.82c-6.3-6.3-16.52-6.3-22.82 0L416 210.36l-45.64-45.64c-6.3-6.3-16.52-6.3-22.82 0l-22.82 22.82c-6.3 6.3-6.3 16.52 0 22.82L370.36 256l-45.63 45.63c-6.3 6.3-6.3 16.52 0 22.82l22.82 22.82c6.3 6.3 16.52 6.3 22.82 0L416 301.64l45.64 45.64c6.3 6.3 16.52 6.3 22.82 0l22.82-22.82c6.3-6.3 6.3-16.52 0-22.82L461.64 256z"},child:[]}]})(e)}function Wu(e){return Nu({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zm233.32-51.08c-11.17-7.33-26.18-4.24-33.51 6.95-7.34 11.17-4.22 26.18 6.95 33.51 66.27 43.49 105.82 116.6 105.82 195.58 0 78.98-39.55 152.09-105.82 195.58-11.17 7.32-14.29 22.34-6.95 33.5 7.04 10.71 21.93 14.56 33.51 6.95C528.27 439.58 576 351.33 576 256S528.27 72.43 448.35 19.97zM480 256c0-63.53-32.06-121.94-85.77-156.24-11.19-7.14-26.03-3.82-33.12 7.46s-3.78 26.21 7.41 33.36C408.27 165.97 432 209.11 432 256s-23.73 90.03-63.48 115.42c-11.19 7.14-14.5 22.07-7.41 33.36 6.51 10.36 21.12 15.14 33.12 7.46C447.94 377.94 480 319.54 480 256zm-141.77-76.87c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 228.28 336 241.63 336 256c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.86z"},child:[]}]})(e)}var qu=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs"],zu=z.memo(function(e){var t=e.src,r=e.autoplay,i=e.muted,n=e.lowLatencyMode,a=e.allowNativeHls,s=e.driftToleranceMs,o=e.immediateManifestAds,l=e.debugAdTiming,u=e.showCustomControls,c=e.hideLoadingIndicator,d=e.onVolumeToggle,h=e.onFullscreenToggle,f=e.onControlClick,v=e.onReady,g=e.wrapperClassName,p=e.wrapperStyle,m=e.className,y=e.style,E=e.controls,k=e.playsInline,T=e.preload,S=e.poster,b=e.children,A=e.licenseKey,L=e.minSegmentsBeforePlay,I=P(e,["src","autoplay","muted","lowLatencyMode","allowNativeHls","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","hideLoadingIndicator","onVolumeToggle","onFullscreenToggle","onControlClick","onReady","wrapperClassName","wrapperStyle","className","style","controls","playsInline","preload","poster","children","licenseKey","minSegmentsBeforePlay"]),R=q.useRef(null),x=q.useRef(null),D=q.useRef(null),C=_(z.useState({showAds:!1,currentIndex:0,totalAds:0}),2),M=C[0],O=C[1],F=_(z.useState(!0),2),N=F[0],U=F[1],B=_(z.useState(!1),2),G=B[0],H=B[1],V=_(z.useState(!1),2),K=V[0],j=V[1],Y=_(z.useState(!1),2),X=Y[0],Q=Y[1],$=_(z.useState(0),2),J=$[0],Z=$[1],ee=_(z.useState(0),2),te=ee[0],re=ee[1],ie=_(z.useState(1),2),ne=ie[0],ae=ie[1],se=_(z.useState(1),2),oe=se[0],le=se[1],ue=_(z.useState(!1),2),ce=ue[0],de=ue[1],he=_(z.useState(!1),2),fe=he[0],ve=he[1],ge=_(z.useState(!0),2),pe=ge[0],me=ge[1],ye=_(z.useState(!1),2),Ee=ye[0],ke=ye[1],Te=_(z.useState(!1),2),Se=Te[0],be=Te[1],Ae=_(z.useState(!1),2),Le=Ae[0],Ie=Ae[1],Re=_(z.useState("undefined"!=typeof window?window.innerWidth:1920),2),we=Re[0],Pe=Re[1],xe=_(z.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),De=xe[0],Ce=xe[1],_e=we<480?.7:we<768?.8:we<1024?.9:1,Me=function(e){if(!isFinite(e))return"0:00:00";var t=Math.floor(e/3600),r=Math.floor(e%3600/60),i=Math.floor(e%60);return"".concat(t,":").concat(r.toString().padStart(2,"0"),":").concat(i.toString().padStart(2,"0"))},Oe=function(e){if(x.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));x.current.setVolume(t)}},Fe=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),Ne=u&&(!Fe||a),Ue=q.useMemo(function(){return qu.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,a,A,n,s]);return q.useEffect(function(){if("undefined"!=typeof window){var e=R.current;if(e&&t){if(!A)return Ie(!0),me(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(Ie(!1),l&&console.log("[StormcloudUI] Initializing player, isLoading=true"),x.current){try{x.current.destroy()}catch(e){}x.current=null}var c={src:t,videoElement:e};void 0!==r&&(c.autoplay=r),void 0!==i&&(c.muted=i),void 0!==n&&(c.lowLatencyMode=n),void 0!==a&&(c.allowNativeHls=a),void 0!==s&&(c.driftToleranceMs=s),void 0!==o&&(c.immediateManifestAds=o),void 0!==l&&(c.debugAdTiming=l),void 0!==u&&(c.showCustomControls=u),void 0!==d&&(c.onVolumeToggle=d),void 0!==h&&(c.onFullscreenToggle=h),void 0!==f&&(c.onControlClick=f),void 0!==A&&(c.licenseKey=A),void 0!==L&&(c.minSegmentsBeforePlay=L);var g=new Ru(c);return x.current=g,g.load().then(function(){var e=g.shouldShowNativeControls();U(e),l&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==v||v(g)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),me(!1),null==v||v(g)}),function(){try{g.destroy()}catch(e){}x.current=null}}}},[Ue]),q.useEffect(function(){if(x.current)try{void 0!==r&&x.current.videoElement&&(x.current.videoElement.autoplay=r),void 0===i||x.current.isShowingAds()||x.current.setMuted(i)}catch(e){console.warn("Failed to update player properties:",e)}},[r,i]),q.useEffect(function(){if(x.current){var e=setInterval(function(){if(x.current){var e=x.current.isShowingAds(),t=x.current.getCurrentAdIndex(),r=x.current.getTotalAdsInBreak();O(function(i){return i.showAds!==e||i.currentIndex!==t||i.totalAds!==r?{showAds:e,currentIndex:t,totalAds:r}:i})}},100);return function(){return clearInterval(e)}}},[]),q.useEffect(function(){if("undefined"!=typeof window&&x.current){var e=function(){x.current&&R.current&&"function"==typeof x.current.resize&&x.current.resize(),Pe(window.innerWidth),Ce(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),q.useEffect(function(){if(x.current&&R.current){var e=setInterval(function(){var e;if(x.current&&R.current){H(x.current.isMuted()),Q(!R.current.paused);var t=R.current.currentTime;Z(isFinite(t)?t:0);var r=R.current.duration;re(isFinite(r)?r:0);var i=R.current.volume;ae(isFinite(i)?Math.max(0,Math.min(1,i)):1);var n=R.current.playbackRate;le(isFinite(n)&&n>0?n:1)}j(document.fullscreenElement===(null===(e=R.current)||void 0===e?void 0:e.parentElement))},200),t=function(){var e;j(document.fullscreenElement===(null===(e=R.current)||void 0===e?void 0:e.parentElement))};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),q.useEffect(function(){if(R.current){var e=function(){var e;R.current&&R.current.offsetHeight;l&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState)},t=function(){var e;l&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState)},r=function(){var e;l&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState)},i=function(){var e;me(!1),D.current&&(clearTimeout(D.current),D.current=null),ke(!1),l&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=function(){var e;me(!1),D.current&&(clearTimeout(D.current),D.current=null),ke(!1),l&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},a=function(){var e;D.current&&clearTimeout(D.current),D.current=window.setTimeout(function(){var e;ke(!0),l&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),l&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},s=function(){var e;me(!1),D.current&&(clearTimeout(D.current),D.current=null),ke(!1),be(!1),l&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=R.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=function(){x.current&&!x.current.isShowingAds()?be(!0):be(!1)},u=function(){be(!0)},c=R.current;return c.addEventListener("loadstart",r),c.addEventListener("loadedmetadata",e),c.addEventListener("loadeddata",t),c.addEventListener("canplay",i),c.addEventListener("canplaythrough",n),c.addEventListener("waiting",a),c.addEventListener("playing",s),c.addEventListener("pause",o),c.addEventListener("ended",u),c.paused&&be(!0),function(){D.current&&(clearTimeout(D.current),D.current=null),c.removeEventListener("loadstart",r),c.removeEventListener("loadedmetadata",e),c.removeEventListener("loadeddata",t),c.removeEventListener("canplay",i),c.removeEventListener("canplaythrough",n),c.removeEventListener("waiting",a),c.removeEventListener("playing",s),c.removeEventListener("pause",o),c.removeEventListener("ended",u)}}},[l]),W.jsxs(W.Fragment,{children:[W.jsx("style",{children:"\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n \n .stormcloud-loading-hidden .stormcloud-loading-indicator {\n display: none !important;\n }\n \n .stormcloud-video-wrapper:fullscreen {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n .stormcloud-video-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n *:fullscreen {\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n }\n "}),W.jsxs("div",{className:"stormcloud-video-wrapper ".concat(g||""),style:w({display:"flex",alignItems:"center",justifyContent:"center",position:K?"fixed":"relative",top:K?0:void 0,left:K?0:void 0,overflow:"hidden",width:K?"100vw":"100%",height:K?"100vh":"auto",minHeight:K?"100vh":"auto",maxWidth:K?"100vw":"100%",maxHeight:K?"100vh":"none",zIndex:K?999999:void 0,backgroundColor:K?"#000":void 0,borderRadius:K?0:void 0,boxShadow:K?"none":void 0},p),children:[W.jsx("video",w({ref:R,className:m,style:w({display:"block",width:"100%",height:K?"100%":"auto",maxWidth:"100%",maxHeight:K?"100%":"none",objectFit:K?"cover":"contain",backgroundColor:"#000",aspectRatio:K?"unset":void 0},y),controls:N&&E&&!u,playsInline:k,preload:T,poster:S},I,{children:b})),(pe||Ee)&&!c&&W.jsx(Ku,{className:"stormcloud-loading-indicator",size:42,color:"white",style:{position:"absolute",top:"calc(50% - 21px)",left:"calc(50% - 21px)",zIndex:20,animation:"spin 1s linear infinite",filter:"drop-shadow(0 3px 6px rgba(0, 0, 0, 0.8))"}}),Le&&W.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.9) 100%)",color:"white",padding:"24px 32px",borderRadius:"16px",backdropFilter:"blur(20px)",border:"2px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.6), inset 0 2px 0 rgba(255, 255, 255, 0.2)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[W.jsx("div",{style:{fontSize:"20px",fontWeight:"bold",marginBottom:"12px",color:"#ffffff",textShadow:"0 2px 4px rgba(0, 0, 0, 0.5)"},children:"License Key Required"}),W.jsxs("div",{style:{fontSize:"14px",lineHeight:"1.5",color:"rgba(255, 255, 255, 0.9)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.3)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",W.jsx("br",{}),"Contact your administrator for licensing information."]})]}),Se&&!pe&&!Ee&&!Le&&!M.showAds&&W.jsx("div",{onClick:function(){var e;R.current&&R.current.paused&&(R.current.src||R.current.currentSrc&&""!==R.current.currentSrc||R.current.readyState>=1?(null===(e=R.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),be(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",borderRadius:"50%",width:"100px",height:"100px",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",border:"3px solid rgba(255, 255, 255, 0.8)",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},onMouseEnter:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(40, 40, 40, 0.9) 100%)",t.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.borderColor="rgba(255, 255, 255, 0.9)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",t.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",t.style.borderColor="rgba(255, 255, 255, 0.8)"},title:"Play",children:W.jsx(Vu,{size:36,color:"white",style:{marginLeft:"6px",filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))"}})}),Ne&&!Le?W.jsx(W.Fragment,{children:W.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.8) 100%)",padding:"20px 16px 16px",zIndex:10},children:[W.jsxs("div",{style:{width:"100%",height:"8px",background:"linear-gradient(90deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%)",borderRadius:"8px",marginBottom:"16px",cursor:"pointer",position:"relative",backdropFilter:"blur(5px)",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"inset 0 2px 4px rgba(0, 0, 0, 0.2)"},onClick:function(e){if(R.current&&te>0&&isFinite(te)){var t=e.currentTarget.getBoundingClientRect(),r=e.clientX-t.left,i=Math.max(0,Math.min(1,r/t.width))*te;isFinite(i)&&i>=0&&i<=te&&(R.current.currentTime=i)}},children:[W.jsx("div",{style:{height:"100%",background:"linear-gradient(90deg, rgba(139, 92, 246, 0.9) 0%, rgba(59, 130, 246, 0.8) 50%, rgba(34, 197, 94, 0.9) 100%)",borderRadius:"8px",width:"".concat(te>0?J/te*100:0,"%"),transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 2px 8px rgba(139, 92, 246, 0.4)"}}),W.jsx("div",{style:{position:"absolute",top:"-6px",right:"".concat(te>0?100-J/te*100:100,"%"),width:"20px",height:"20px",background:"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(240, 240, 240, 0.9) 100%)",borderRadius:"50%",border:"3px solid rgba(139, 92, 246, 0.8)",boxShadow:"0 4px 16px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.8)",transform:"translateX(50%)",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"}})]}),W.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",flexWrap:we<768?"wrap":"nowrap",gap:"".concat(8*_e,"px")},children:[W.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*_e,"px"),flexWrap:we<480?"wrap":"nowrap"},children:[W.jsx("button",{onClick:function(){var e;R.current&&(R.current.paused?R.current.src||R.current.currentSrc&&""!==R.current.currentSrc||R.current.readyState>=1?(null===(e=R.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),be(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"):(R.current.pause(),be(!0)))},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",backdropFilter:"blur(12px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(10*_e,"px"),borderRadius:"".concat(16*_e,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)",minWidth:"".concat(48*_e,"px"),minHeight:"".concat(48*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)",t.style.boxShadow="0 12px 48px rgba(0, 0, 0, 0.6), 0 6px 24px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.4)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",t.style.boxShadow="0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)"},title:X?"Pause":"Play",children:X?W.jsx(Hu,{size:Math.max(16,20*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Vu,{size:Math.max(16,20*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),W.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)},children:[W.jsx("button",{onClick:function(){x.current&&x.current.toggleMute(),d&&d()},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*_e,"px"),borderRadius:"".concat(16*_e,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*_e,"px"),minHeight:"".concat(44*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:G?"Unmute":"Mute",children:G||0===ne?W.jsx(Yu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):ne<.5?W.jsx(ju,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Wu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),ce&&W.jsxs(W.Fragment,{children:[W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)}}),W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.88) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(15px)",padding:"10px 14px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){de(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.6), 0 6px 16px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 0 24px rgba(59, 130, 246, 0.3)",e.currentTarget.style.borderColor="rgba(59, 130, 246, 0.4)"},onMouseLeave:function(e){de(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.15)"},children:W.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseEnter:function(e){},onMouseLeave:function(e){},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){if(t){var r=t.getBoundingClientRect(),i=e.clientY-r.top,n=1-Math.max(0,Math.min(1,i/r.height));Oe(n)}},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect(),a=e.clientY-n.top,s=1-Math.max(0,Math.min(1,a/n.height));Oe(s)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),r=e.clientY-t.top,i=1-Math.max(0,Math.min(1,r/t.height));Oe(i)},children:[W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.15) 100%)",borderRadius:"4px",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.2)"}}),W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(G?0:ne),"%"),background:"linear-gradient(180deg, rgba(96, 165, 250, 1) 0%, rgba(59, 130, 246, 0.95) 50%, rgba(37, 99, 235, 0.9) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 8px rgba(59, 130, 246, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.3)"}}),W.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(G?0:ne),"% - 7px)"),left:"50%",transform:"translateX(-50%)",width:"14px",height:"14px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 3px 10px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(59, 130, 246, 0.5), 0 0 20px rgba(59, 130, 246, 0.6)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),W.jsxs("div",{style:{fontSize:"".concat(14*_e,"px"),fontFamily:"monospace",color:"rgba(255, 255, 255, 0.9)",display:we<480?"none":"block"},children:[Me(J)," / ",Me(te)]})]}),W.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*_e,"px")},children:[W.jsxs("div",{style:{position:"relative",display:we<600?"none":"block"},children:[W.jsxs("button",{onClick:function(){return ve(!fe)},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*_e,"px ").concat(14*_e,"px"),borderRadius:"".concat(14*_e,"px"),fontSize:"".concat(14*_e,"px"),fontFamily:"monospace",fontWeight:"700",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(56*_e,"px"),minHeight:"".concat(40*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 32px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:"Playback Speed",children:[oe,"x"]}),fe&&W.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"12px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.95) 100%)",backdropFilter:"blur(20px)",borderRadius:"12px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"90px",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1)"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(function(e){return W.jsxs("button",{onClick:function(){return t=e,R.current&&isFinite(t)&&t>0&&(R.current.playbackRate=t),void ve(!1);var t},style:{display:"block",width:"100%",padding:"10px 16px",background:oe===e?"linear-gradient(135deg, rgba(99, 102, 241, 0.8) 0%, rgba(139, 92, 246, 0.6) 100%)":"transparent",border:"none",color:"white",cursor:"pointer",fontSize:"13px",fontFamily:"monospace",fontWeight:"600",textAlign:"center",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",borderBottom:2!==e?"1px solid rgba(255, 255, 255, 0.05)":"none"},onMouseEnter:function(t){oe!==e&&(t.target.style.background="linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%)")},onMouseLeave:function(t){oe!==e&&(t.target.style.background="transparent")},children:[e,"x"]},e)})})]}),W.jsx("button",{onClick:function(){h?h():x.current&&x.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*_e,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*_e,"px"),borderRadius:"".concat(16*_e,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*_e,"px"),minHeight:"".concat(44*_e,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:K?"Exit Fullscreen":"Enter Fullscreen",children:K?W.jsx(Bu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Gu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 0 0 transparent)"}})})]})]})]})}):u&&!Le&&W.jsxs("div",{style:{position:"absolute",bottom:"".concat(10*_e,"px"),right:"".concat(10*_e,"px"),transform:"none",display:"flex",flexDirection:De?"column":"row",gap:"".concat(10*_e,"px"),zIndex:10},children:[W.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)},children:[W.jsx("button",{onClick:function(){x.current&&x.current.toggleMute(),d&&d()},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*_e,"px"),padding:"".concat(8*_e,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*_e,"px"),minHeight:"".concat(46*_e,"px")},title:G?"Unmute":"Mute",children:G||0===ne?W.jsx(Yu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):ne<.5?W.jsx(ju,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):W.jsx(Wu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})}),ce&&W.jsxs(W.Fragment,{children:[W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return de(!0)},onMouseLeave:function(){return de(!1)}}),W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.96) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(20px)",padding:"10px 14px",borderRadius:"14px",border:"2px solid rgba(255, 255, 255, 0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){de(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), 0 6px 16px rgba(0, 0, 0, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 24px rgba(96, 165, 250, 0.4)",e.currentTarget.style.borderColor="rgba(96, 165, 250, 0.8)"},onMouseLeave:function(e){de(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.7)"},children:W.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){if(t){var r=t.getBoundingClientRect(),i=e.clientY-r.top,n=1-Math.max(0,Math.min(1,i/r.height));Oe(n)}},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect(),a=e.clientY-n.top,s=1-Math.max(0,Math.min(1,a/n.height));Oe(s)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),r=e.clientY-t.top,i=1-Math.max(0,Math.min(1,r/t.height));Oe(i)},children:[W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.85) 0%, rgba(255, 255, 255, 0.5) 100%)",borderRadius:"4px",border:"1px solid rgba(255, 255, 255, 0.4)",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.3)"}}),W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(G?0:ne),"%"),background:"linear-gradient(180deg, rgba(125, 211, 252, 1) 0%, rgba(96, 165, 250, 0.98) 50%, rgba(59, 130, 246, 0.95) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 12px rgba(96, 165, 250, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.4)"}}),W.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(G?0:ne),"% - 8px)"),left:"50%",transform:"translateX(-50%)",width:"16px",height:"16px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",border:"2px solid rgba(96, 165, 250, 0.9)",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.6), 0 0 0 3px rgba(96, 165, 250, 0.6), 0 0 24px rgba(96, 165, 250, 0.7)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),W.jsx("button",{onClick:function(){h?h():x.current&&x.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*_e,"px"),padding:"".concat(8*_e,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*_e,"px"),minHeight:"".concat(46*_e,"px")},title:K?"Exit Fullscreen":"Enter Fullscreen",children:K?W.jsx(Bu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):W.jsx(Gu,{size:Math.max(14,16*_e),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})})]}),f&&W.jsx("div",{onClick:f,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var r,i,n,a,s,o;try{for(var l=C(qu),u=l.next();!u.done;u=l.next()){if(e[v=u.value]!==t[v])return!1}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}try{for(var c=C(["autoplay","muted","controls","showCustomControls","className","style","wrapperClassName","wrapperStyle","playsInline","preload","poster","children"]),d=c.next();!d.done;d=c.next()){if(e[v=d.value]!==t[v])return!1}}catch(e){n={error:e}}finally{try{d&&!d.done&&(a=c.return)&&a.call(c)}finally{if(n)throw n.error}}try{for(var h=C(["onReady","onVolumeToggle","onFullscreenToggle","onControlClick"]),f=h.next();!f.done;f=h.next()){var v;if(e[v=f.value]!==t[v])return!1}}catch(e){s={error:e}}finally{try{f&&!f.done&&(o=h.return)&&o.call(h)}finally{if(s)throw s.error}}return!0}),Xu=function(){},Qu={playing:!1,loop:!1,controls:!0,volume:1,muted:!1,playbackRate:1,width:"100%",height:"auto",style:{},progressInterval:1e3,playsInline:!1,autoplay:!1,preload:"metadata",poster:"",className:"",wrapperClassName:"",wrapperStyle:{},allowNativeHls:!1,lowLatencyMode:!1,driftToleranceMs:1e3,immediateManifestAds:!0,debugAdTiming:!1,showCustomControls:!1,hideLoadingIndicator:!1,licenseKey:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:Xu,onPlay:Xu,onPause:Xu,onBuffer:Xu,onBufferEnd:Xu,onEnded:Xu,onError:Xu,onDuration:Xu,onSeek:Xu,onProgress:Xu,onVolumeToggle:Xu,onFullscreenToggle:Xu,onControlClick:Xu},$u=q.lazy,Ju=function(e,t){var r=w({},e);return t.forEach(function(e){delete r[e]}),r},Zu=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},ec=function(e){for(var t,r,i=[],n=1;n<arguments.length;n++)i[n-1]=arguments[n];if(!i.length)return e;var a=i.shift();if(tc(e)&&tc(a))for(var s in a)tc(a[s])?(e[s]||Object.assign(e,((t={})[s]={},t)),ec(e[s],a[s])):Object.assign(e,((r={})[s]=a[s],r));return ec.apply(void 0,M([e],_(i),!1))},tc=function(e){return e&&"object"===S(e)&&!Array.isArray(e)},rc="undefined"!=typeof window&&window.document,ic="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,nc=rc&&/iPad|iPhone|iPod/.test(navigator.userAgent),ac=rc&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),sc=/\.(m3u8)($|\?)/i,oc=/\/hls\//i,lc=/\.(mpd)($|\?)/i,uc=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,cc=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,dc={hls:function(e){return!(!e||"string"!=typeof e)&&(sc.test(e)||oc.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&lc.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&uc.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&cc.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(uc.test(e)||cc.test(e))}},hc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return x(t,void 0,void 0,function(){var e,t,r,i,n,a,s,o;return D(this,function(l){switch(l.label){case 0:if(!this.props.videoElement||!this.props.src)return[2];l.label=1;case 1:return l.trys.push([1,3,,4]),this.player&&(this.player.destroy(),this.player=null),e={src:this.props.src,videoElement:this.props.videoElement},void 0!==this.props.autoplay&&(e.autoplay=this.props.autoplay),void 0!==this.props.muted&&(e.muted=this.props.muted),void 0!==this.props.lowLatencyMode&&(e.lowLatencyMode=this.props.lowLatencyMode),void 0!==this.props.allowNativeHls&&(e.allowNativeHls=this.props.allowNativeHls),void 0!==this.props.driftToleranceMs&&(e.driftToleranceMs=this.props.driftToleranceMs),void 0!==this.props.immediateManifestAds&&(e.immediateManifestAds=this.props.immediateManifestAds),void 0!==this.props.debugAdTiming&&(e.debugAdTiming=this.props.debugAdTiming),void 0!==this.props.showCustomControls&&(e.showCustomControls=this.props.showCustomControls),void 0!==this.props.onVolumeToggle&&(e.onVolumeToggle=this.props.onVolumeToggle),void 0!==this.props.onFullscreenToggle&&(e.onFullscreenToggle=this.props.onFullscreenToggle),void 0!==this.props.onControlClick&&(e.onControlClick=this.props.onControlClick),void 0!==this.props.licenseKey&&(e.licenseKey=this.props.licenseKey),void 0!==this.props.adFailsafeTimeoutMs&&(e.adFailsafeTimeoutMs=this.props.adFailsafeTimeoutMs),void 0!==this.props.minSegmentsBeforePlay&&(e.minSegmentsBeforePlay=this.props.minSegmentsBeforePlay),this.player=new Ru(e),null===(i=(r=this.props).onMount)||void 0===i||i.call(r,this),[4,this.player.load()];case 2:return l.sent(),this.mounted&&(null===(a=(n=this.props).onReady)||void 0===a||a.call(n)),[3,4];case 3:return t=l.sent(),this.mounted&&(null===(o=(s=this.props).onError)||void 0===o||o.call(s,t)),[3,4];case 4:return[2]}})})},t.play=function(){var e,r,i;if(t.props.videoElement){var n=t.props.videoElement;n.src||n.currentSrc&&""!==n.currentSrc||n.readyState>=1?(null===(e=n.play())||void 0===e||e.catch(function(e){var r,i;console.error("[HlsPlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}),null===(i=(r=t.props).onPlay)||void 0===i||i.call(r)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},t.pause=function(){var e,r;t.props.videoElement&&(t.props.videoElement.pause(),null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"player"===e?t.player:"video"===e?t.props.videoElement:"hls"===e&&t.player?t.player.hls:null},t}return R(t,e),t.prototype.componentDidMount=function(){this.mounted=!0,this.load()},t.prototype.componentWillUnmount=function(){this.mounted=!1,this.player&&(this.player.destroy(),this.player=null)},t.prototype.componentDidUpdate=function(e){e.src!==this.props.src&&this.load()},t.prototype.render=function(){return null},t.displayName="HlsPlayer",t.canPlay=dc.hls,t}(q.Component),fc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,r;if(t.props.videoElement&&t.props.src){var i=t.props.videoElement,n=function(){var e,r;t.mounted&&!t.ready&&(t.ready=!0,null===(r=(e=t.props).onReady)||void 0===r||r.call(e))},a=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPlay)||void 0===r||r.call(e))},s=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},o=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onEnded)||void 0===r||r.call(e))},l=function(e){var r,i;t.mounted&&(null===(i=(r=t.props).onError)||void 0===i||i.call(r,e))},u=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onLoaded)||void 0===r||r.call(e))};return i.addEventListener("loadedmetadata",n),i.addEventListener("play",a),i.addEventListener("pause",s),i.addEventListener("ended",o),i.addEventListener("error",l),i.addEventListener("loadeddata",u),i.src=t.props.src,void 0!==t.props.autoplay&&(i.autoplay=t.props.autoplay),void 0!==t.props.muted&&(i.muted=t.props.muted),void 0!==t.props.loop&&(i.loop=t.props.loop),void 0!==t.props.controls&&(i.controls=t.props.controls),void 0!==t.props.playsInline&&(i.playsInline=t.props.playsInline),void 0!==t.props.preload&&(i.preload=t.props.preload),void 0!==t.props.poster&&(i.poster=t.props.poster),null===(r=(e=t.props).onMount)||void 0===r||r.call(e,t),function(){i.removeEventListener("loadedmetadata",n),i.removeEventListener("play",a),i.removeEventListener("pause",s),i.removeEventListener("ended",o),i.removeEventListener("error",l),i.removeEventListener("loadeddata",u)}}},t.play=function(){var e;if(t.props.videoElement){var r=t.props.videoElement;r.src||r.currentSrc&&""!==r.currentSrc||r.readyState>=1?null===(e=r.play())||void 0===e||e.catch(function(e){var r,i;console.error("[FilePlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},t.pause=function(){t.props.videoElement&&t.props.videoElement.pause()},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.setLoop=function(e){t.props.videoElement&&(t.props.videoElement.loop=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"video"===e?t.props.videoElement:null},t.enablePIP=function(){return x(t,void 0,void 0,function(){var e;return D(this,function(t){switch(t.label){case 0:if(!this.props.videoElement||!("requestPictureInPicture"in this.props.videoElement))return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.props.videoElement.requestPictureInPicture()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Picture-in-Picture failed:",e),[3,4];case 4:return[2]}})})},t.disablePIP=function(){return x(t,void 0,void 0,function(){var e;return D(this,function(t){switch(t.label){case 0:if(!document.pictureInPictureElement)return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,document.exitPictureInPicture()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Exit Picture-in-Picture failed:",e),[3,4];case 4:return[2]}})})},t}return R(t,e),t.prototype.componentDidMount=function(){this.mounted=!0,this.load()},t.prototype.componentWillUnmount=function(){this.mounted=!1},t.prototype.componentDidUpdate=function(e){e.src!==this.props.src&&this.load()},t.prototype.render=function(){return null},t.displayName="FilePlayer",t.canPlay=dc.file,t}(q.Component),vc=[{key:"hls",name:"HLS Player",canPlay:dc.hls,lazyPlayer:$u(function(){return Promise.resolve({default:hc})})},{key:"file",name:"File Player",canPlay:dc.file,canEnablePIP:function(e){return dc.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:$u(function(){return Promise.resolve({default:fc})})}],gc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.mounted=!1,t.isReady=!1,t.isPlaying=!1,t.isLoading=!0,t.loadOnReady=null,t.startOnPlay=!0,t.seekOnPlay=null,t.onDurationCalled=!1,t.handlePlayerMount=function(e){t.player||(t.player=e,t.player.load(t.props.src)),t.progress()},t.getInternalPlayer=function(e){return t.player?t.player.getInternalPlayer(e):null},t.progress=function(){var e,r;if(t.props.src&&t.player&&t.isReady){var i=t.getCurrentTime()||0,n=t.getSecondsLoaded(),a=t.getDuration();if(a){var s={playedSeconds:i,played:i/a,loaded:0,loadedSeconds:0};null!==n&&(s.loadedSeconds=n,s.loaded=n/a),s.playedSeconds===t.prevPlayed&&s.loadedSeconds===t.prevLoaded||null===(r=(e=t.props).onProgress)||void 0===r||r.call(e,s),t.prevPlayed=s.playedSeconds,t.prevLoaded=s.loadedSeconds}}t.progressTimeout=window.setTimeout(t.progress,t.props.progressInterval||1e3)},t.handleReady=function(){if(t.mounted){t.isReady=!0,t.isLoading=!1;var e=t.props,r=e.onReady,i=e.playing,n=e.volume,a=e.muted;r(),a||null===n||t.player.setVolume(n),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):i&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,r=e.onStart,i=e.onPlay,n=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==n&&t.player.setPlaybackRate(n),null==r||r(),t.startOnPlay=!1),null==i||i(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var r,i;t.isPlaying=!1,t.isLoading||null===(i=(r=t.props).onPause)||void 0===i||i.call(r,e)},t.handleEnded=function(){var e=t.props,r=e.activePlayer,i=e.loop,n=e.onEnded;r.loopOnEnded&&i&&t.seekTo(0),i||(t.isPlaying=!1,null==n||n())},t.handleError=function(){for(var e,r,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];t.isLoading=!1,null===(r=(e=t.props).onError)||void 0===r||r.call(e,i[0],i[1],i[2],i[3])},t.handleDurationCheck=function(){var e,r;clearTimeout(t.durationCheckTimeout);var i=t.getDuration();i?t.onDurationCalled||(null===(r=(e=t.props).onDuration)||void 0===r||r.call(e,i),t.onDurationCalled=!0):t.durationCheckTimeout=window.setTimeout(t.handleDurationCheck,100)},t.handleLoaded=function(){t.isLoading=!1},t}return R(t,e),t.prototype.componentDidMount=function(){this.mounted=!0},t.prototype.componentWillUnmount=function(){clearTimeout(this.progressTimeout),clearTimeout(this.durationCheckTimeout),this.mounted=!1},t.prototype.componentDidUpdate=function(e){var t=this;if(this.player){var r=this.props,i=r.src,n=r.playing,a=r.volume,s=r.muted,o=r.playbackRate,l=r.loop,u=r.activePlayer;if(e.src!==i){if(this.isLoading&&!u.forceLoad&&!Zu(i))return console.warn("StormcloudPlayer: the attempt to load ".concat(i," is being deferred until the player has loaded")),void(this.loadOnReady=i||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(i,this.isReady)}e.playing||!n||this.isPlaying||this.player.play(),e.playing&&!n&&this.isPlaying&&this.player.pause(),e.volume!==a&&null!==a&&this.player.setVolume(a),e.muted!==s&&(s?this.player.mute():(this.player.unmute(),null!==a&&setTimeout(function(){return t.player.setVolume(a)}))),e.playbackRate!==o&&this.player.setPlaybackRate&&this.player.setPlaybackRate(o),e.loop!==l&&this.player.setLoop&&this.player.setLoop(l)}},t.prototype.getDuration=function(){return this.isReady?this.player.getDuration():null},t.prototype.getCurrentTime=function(){return this.isReady?this.player.getCurrentTime():null},t.prototype.getSecondsLoaded=function(){return this.isReady?this.player.getSecondsLoaded():null},t.prototype.seekTo=function(e,t,r){var i=this;if(this.isReady){if(t?"fraction"===t:e>0&&e<1){var n=this.player.getDuration();return n?void this.player.seekTo(n*e,r):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,r)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){i.seekOnPlay=null},5e3))},t.prototype.render=function(){var e=this.props.activePlayer;return e?z.createElement(e,w(w({},this.props),{onMount:this.handlePlayerMount,onReady:this.handleReady,onPlay:this.handlePlay,onPause:this.handlePause,onEnded:this.handleEnded,onLoaded:this.handleLoaded,onError:this.handleError})):null},t.displayName="Player",t.defaultProps=Qu,t}(q.Component),pc="undefined"!=typeof window&&window.document,mc="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,yc=pc||mc?q.Suspense:function(){return null},Ec=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","adFailsafeTimeoutMs","minSegmentsBeforePlay","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],kc=[],Tc=function(e,t){var r;return r=function(r){function i(){var i=r.apply(this,M([],_(arguments),!1))||this;return i.state={showPreview:!1},i.references={wrapper:function(e){i.wrapper=e},player:function(e){i.player=e}},i.getActivePlayer=function(r){var i,n;if(!r)return null;try{for(var a=C(M(M([],_(kc),!1),_(e),!1)),s=a.next();!s.done;s=a.next()){var o=s.value;if(o.canPlay(r))return o}}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(i)throw i.error}}return t||null},i.getAttributes=function(e){return Ju(i.props,Ec)},i.handleReady=function(){var e,t;null===(t=(e=i.props).onReady)||void 0===t||t.call(e,i)},i.seekTo=function(e,t,r){if(!i.player)return null;i.player.seekTo(e,t,r)},i.getCurrentTime=function(){return i.player?i.player.getCurrentTime():null},i.getSecondsLoaded=function(){return i.player?i.player.getSecondsLoaded():null},i.getDuration=function(){return i.player?i.player.getDuration():null},i.getInternalPlayer=function(e){return void 0===e&&(e="player"),i.player?i.player.getInternalPlayer(e):null},i.renderActivePlayer=function(e){if(!e)return null;var t=i.getActivePlayer(e);return t?z.createElement(gc,w(w({},i.props),{key:t.key,ref:i.references.player,activePlayer:t.lazyPlayer||t,onReady:i.handleReady})):null},i}return R(i,r),i.prototype.render=function(){var e=this.props,t=e.src,r=e.style,i=e.width,n=e.height,a=e.fallback,s=e.wrapper,o=this.getAttributes(t),l="string"==typeof s?this.references.wrapper:void 0;return z.createElement(s,w({ref:l,style:w(w({},r),{width:i,height:n})},o),z.createElement(yc,{fallback:a},this.renderActivePlayer(t)))},i}(q.Component),r.displayName="StormcloudPlayer",r.defaultProps=w(w({},Qu),{fallback:null,wrapper:"div"}),r.addCustomPlayer=function(e){kc.push(e)},r.removeCustomPlayers=function(){kc.length=0},r.canPlay=function(t){var r,i;try{for(var n=C(M(M([],_(kc),!1),_(e),!1)),a=n.next();!a.done;a=n.next()){if(a.value.canPlay(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r.canEnablePIP=function(t){var r,i;try{for(var n=C(M(M([],_(kc),!1),_(e),!1)),a=n.next();!a.done;a=n.next()){var s=a.value;if(s.canEnablePIP&&s.canEnablePIP(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r},Sc=Tc(vc,vc[vc.length-1]),bc=null;function Ac(){var e,t,r,i,n,a=navigator.userAgent,s=navigator.platform,o=navigator.vendor||"",l=navigator.maxTouchPoints||0,u=navigator.deviceMemory||null,c=navigator.hardwareConcurrency||1,d={width:null===screen||void 0===screen?void 0:screen.width,height:null===screen||void 0===screen?void 0:screen.height,availWidth:null===screen||void 0===screen?void 0:screen.availWidth,availHeight:null===screen||void 0===screen?void 0:screen.availHeight,orientation:(null===(e=null===screen||void 0===screen?void 0:screen.orientation)||void 0===e?void 0:e.type)||"",pixelDepth:null===screen||void 0===screen?void 0:screen.pixelDepth},h="desktop",f="Unknown",v="Unknown",g="",p=!1,m=!1,y=!1;if(a.includes("Web0S")){f="LG",v="webOS",p=!0,h="tv";var E=a.match(/Web0S\/([^\s]+)/);g=E?"webOS ".concat(E[1]):"webOS TV"}else if(a.includes("Tizen")){f="Samsung",v="Tizen",p=!0,h="tv";var k=a.match(/Tizen\/([^\s]+)/),T=a.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=k?"Tizen ".concat(k[1]," ").concat(T).trim():"Tizen TV"}else a.includes("Philips")?(f="Philips",v="Saphi",p=!0,h="tv"):a.includes("Sharp")||a.includes("AQUOS")?(f="Sharp",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("Sony")||o.includes("Sony"))?(f="Sony",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("NetCast")||a.includes("LG"))?(f="LG",v="Android TV",p=!0,h="tv"):a.includes(" Roku")||a.includes("Roku/")?(f="Roku",v="Roku OS",p=!0,h="tv"):a.includes("AppleTV")&&(f="Apple",v="tvOS",p=!0,h="tv");if(a.includes("Android")){m=!0,v="Android",h=/Mobile/.test(a)?"mobile":"tablet",a.includes("Android")&&(0===l||a.includes("Google TV")||a.includes("XiaoMi"))&&(h="tv",p=!0,f="Unknown"===f?"Android TV":f);var S=a.match(/\(([^)]*Android[^)]*)\)/);S&&S[1]&&(g=S[1])}return/iPad|iPhone|iPod/.test(a)&&(v="iOS",h="mobile",f="Apple",navigator.maxTouchPoints>1&&/iPad/.test(a)&&(h="tablet")),m||p||/Mobile/.test(a)||(a.includes("Windows")?(v="Windows",h="desktop"):a.includes("Mac")&&!/iPhone/.test(a)?(v="macOS",h="desktop",l>1&&(h="tablet")):a.includes("Linux")&&(v="Linux",h="desktop")),"Unknown"===f&&((o.includes("Google")||a.includes("Chrome"))&&(f="Google"),o.includes("Apple")&&(f="Apple"),(o.includes("Samsung")||a.includes("SM-"))&&(f="Samsung")),y=/wv|WebView|Linux; U;/.test(a),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),n=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(r=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===r?void 0:r.angle),{brand:f,os:v,model:g||a.substring(0,50)+"...",deviceType:h,isSmartTV:p,isAndroid:m,isWebView:y,isWebApp:n,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:a,vendor:o,platform:s,screen:d,hardwareConcurrency:c,deviceMemory:u,maxTouchPoints:l,language:navigator.language,languages:(null===(i=navigator.languages)||void 0===i?void 0:i.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function Lc(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u,c,d,h,f;return D(this,function(v){switch(v.label){case 0:if(bc)return[2,bc];if(t=JSON.stringify(e),"undefined"==typeof crypto||!crypto.subtle||!crypto.subtle.digest)return[3,5];v.label=1;case 1:return v.trys.push([1,4,,5]),[4,crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3]))];case 2:if(v.sent(),r=void 0,"undefined"!=typeof TextEncoder)r=(new TextEncoder).encode(t);else{for(i=unescape(encodeURIComponent(t)),n=new Uint8Array(i.length),u=0;u<i.length;u++)n[u]=i.charCodeAt(u);r=n}return[4,crypto.subtle.digest("SHA-256",r)];case 3:return a=v.sent(),s=Array.from(new Uint8Array(a)),o=s.map(function(e){return e.toString(16).padStart(2,"0")}).join(""),bc=o,[2,o];case 4:return v.sent(),console.warn("[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash"),[3,5];case 5:for(l=0,u=0;u<t.length;u++)c=t.charCodeAt(u),l=(l<<5)-l+c,l&=l;return d=Math.abs(l).toString(16).padStart(8,"0"),h=Date.now().toString(16).padStart(12,"0"),f=Math.random().toString(16).substring(2,14).padStart(12,"0"),[2,bc=(d+h+f).padEnd(64,"0")]}})})}var Ic=[".flv",".f4v",".swf",".wmv",".avi",".mov",".mkv",".mp4",".webm"];function Rc(e){try{var t=new URL(e,"http://dummy").pathname;return-1===(r=t.lastIndexOf("."))?"":t.slice(r).toLowerCase()}catch(t){var r;return-1===(r=e.lastIndexOf("."))?"":(e.slice(r).split(/[?#]/)[0]||"").toLowerCase()}}e.IS_BROWSER=rc,e.IS_GLOBAL=ic,e.IS_IOS=nc,e.IS_SAFARI=ac,e.SUPPORTS_DASH=function(){if(!rc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!rc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=Sc,e.StormcloudVideoPlayer=Ru,e.StormcloudVideoPlayerComponent=zu,e.canPlay=dc,e.createAdStormPlayer=Su,e.createHlsAdPlayer=function(e,t){var r,i,n,a,s,o=!1,l=!1,u=Math.max(0,Math.min(1,e.volume||1)),c=new Map,d=null==t?void 0:t.licenseKey,h=null==t?void 0:t.mainHlsInstance,f=!1,v=[],g={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function p(e,t){var r,i,n=c.get(e);if(n)try{for(var a=C(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("[HlsAdPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function m(e){e&&0!==e.length&&e.forEach(function(e){try{var t=e;s&&(t="".concat(t).concat(t.includes("?")?"&":"?","session_id=").concat(s)),d&&(t="".concat(t).concat(t.includes("?")?"&":"?","license_key=").concat(d)),new Image(1,1).src=t,console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(t))}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}function y(e){if(0===e.length)throw new Error("No media files available");var t=e[0];if(!t)throw new Error("No media files available");if(1===e.length)return t;var r=function(){if(!h||!h.levels)return null;var e=h.currentLevel;if(-1===e||!h.levels[e]){var t=h.loadLevel;if(-1!==t&&h.levels[t]){var r=h.levels[t];return{width:r.width||1920,height:r.height||1080,bitrate:r.bitrate||5e6}}return null}var i=h.levels[e];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}();if(!r)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",r);var i=e.map(function(e){var t=Math.abs(e.width-r.width)+Math.abs(e.height-r.height),i=1e3*(e.bitrate||5e3),n=Math.abs(i-r.bitrate);return{file:e,score:2*t+n/1e3,resolutionDiff:t,bitrateDiff:n}});i.sort(function(e,t){return e.score-t.score});var n=i[0];return n?(console.log("[HlsAdPlayer] Selected media file:",{url:n.file.url,resolution:"".concat(n.file.width,"x").concat(n.file.height),bitrate:n.file.bitrate,score:n.score,resolutionDiff:n.resolutionDiff,bitrateDiff:n.bitrateDiff}),n.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}function E(e){var t,r,i,n;try{var a=(new DOMParser).parseFromString(e,"text/xml"),s=a.querySelector("parsererror");if(s)return console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",s.textContent),null;var o=a.querySelector("Ad");if(!o)return console.warn("[HlsAdPlayer] No Ad element found in VAST XML"),null;var l=o.getAttribute("id")||"unknown",u=(null===(t=a.querySelector("AdTitle"))||void 0===t?void 0:t.textContent)||"Ad",c="empty"===l||u.toLowerCase().includes("no ad available")||"no ad available"===u.toLowerCase(),d=((null===(r=a.querySelector("Duration"))||void 0===r?void 0:r.textContent)||"00:00:30").split(":"),h=3600*parseInt(d[0]||"0",10)+60*parseInt(d[1]||"0",10)+parseInt(d[2]||"0",10),f=a.querySelectorAll("MediaFile"),v=[];if(console.log("[HlsAdPlayer] Found ".concat(f.length," MediaFile element(s) in VAST XML")),f.forEach(function(e,t){var r,i=e.getAttribute("type")||"",n=(null===(r=e.textContent)||void 0===r?void 0:r.trim())||"",a=e.getAttribute("width")||"",s=e.getAttribute("height")||"";console.log("[HlsAdPlayer] MediaFile ".concat(t,': type="').concat(i,'", url="').concat(n,'", width="').concat(a,'", height="').concat(s,'"'));var o=n;if((n=function(e){return".flv"===Rc(e)?e.replace(/\.flv(\?|$)/i,".mp4$1"):e}(n))!==o&&console.log("[HlsAdPlayer] Converted FLV to MP4: ".concat(o," -> ").concat(n)),function(e){var t=Rc(e);return-1!==Ic.indexOf(t)}(n)){var l=Rc(n);console.log("[HlsAdPlayer] MediaFile ".concat(t," ignored: unsupported format (extension: ").concat(l,", declared type: ").concat(i,")"))}else if("application/x-mpegURL"===i||i.includes("m3u8")){if(!n)return void console.warn("[HlsAdPlayer] MediaFile ".concat(t," has HLS type but empty URL"));var u=e.getAttribute("bitrate"),c=u?parseInt(u,10):void 0;v.push({url:n,type:i,width:parseInt(a||"1920",10),height:parseInt(s||"1080",10),bitrate:c&&c>0?c:void 0}),console.log("[HlsAdPlayer] Added HLS MediaFile: ".concat(n))}else console.log("[HlsAdPlayer] MediaFile ".concat(t,' ignored (type="').concat(i,'" is not HLS)'))}),0===v.length)return c?console.warn("[HlsAdPlayer] No ads available (VAST response indicates no ads)"):console.warn("[HlsAdPlayer] No HLS media files found in VAST XML"),null;var g={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};a.querySelectorAll("Impression").forEach(function(e){var t,r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&g.impression.push(r)}),a.querySelectorAll("Tracking").forEach(function(e){var t,r=e.getAttribute("event"),i=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(r&&i){var n=r;g[n]&&g[n].push(i)}});var p=null===(n=null===(i=a.querySelector("ClickThrough"))||void 0===i?void 0:i.textContent)||void 0===n?void 0:n.trim();return{id:l,title:u,duration:h,mediaFiles:v,trackingUrls:g,clickThrough:p}}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),null}}function k(e){return x(this,void 0,void 0,function(){var t,r;return D(this,function(i){switch(i.label){case 0:return[4,fetch(e)];case 1:if(!(t=i.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(t.statusText));return[4,t.text()];case 2:return r=i.sent(),console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",r.substring(0,2e3)),[2,E(r)]}})})}function T(){r&&a&&(r.addEventListener("timeupdate",function(){if(a&&r){var e=r.currentTime/a.duration;e>=.25&&!g.firstQuartile&&(g.firstQuartile=!0,m(a.trackingUrls.firstQuartile)),e>=.5&&!g.midpoint&&(g.midpoint=!0,m(a.trackingUrls.midpoint)),e>=.75&&!g.thirdQuartile&&(g.thirdQuartile=!0,m(a.trackingUrls.thirdQuartile))}}),r.addEventListener("playing",function(){a&&!g.start&&(g.start=!0,m(a.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing"))}),r.addEventListener("ended",function(){a&&!g.complete&&(g.complete=!0,m(a.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),function(){console.log("[HlsAdPlayer] Handling ad completion"),o=!1,S(!1),p("content_resume");var t=window.setTimeout(function(){if(f)console.log("[HlsAdPlayer] Player destroyed, skipping post-completion check");else{"true"===e.dataset.stormcloudAdPlaying&&(console.log("[HlsAdPlayer] Still in ad pod - keeping ad container visible (black screen)"),n&&(n.style.display="flex",n.style.pointerEvents="auto"));var r=v.indexOf(t);-1!==r&&v.splice(r,1)}},50);v.push(t)}())}),r.addEventListener("error",function(e){console.error("[HlsAdPlayer] Ad video error:",e),a&&m(a.trackingUrls.error),b()}),r.addEventListener("volumechange",function(){a&&(r.muted?m(a.trackingUrls.mute):m(a.trackingUrls.unmute))}),r.addEventListener("pause",function(){a&&!r.ended&&m(a.trackingUrls.pause)}),r.addEventListener("play",function(){a&&r.currentTime>0&&m(a.trackingUrls.resume)}))}function S(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function b(){console.log("[HlsAdPlayer] Handling ad error"),o=!1,S(!1);var r=e.muted;e.muted=l,e.volume=l?0:u,console.log("[HlsAdPlayer] Restored mute state: ".concat(r," -> ").concat(l)),n&&(n.style.display="none",n.style.pointerEvents="none"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),p("ad_error")}return{initialize:function(){var t;if(console.log("[HlsAdPlayer] Initializing"),!n){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),n=r}},requestAds:function(t){return x(this,void 0,void 0,function(){var r,i,n,l,u;return D(this,function(c){switch(c.label){case 0:if(console.log("[HlsAdPlayer] Requesting ads for duration:",t),o)return console.warn("[HlsAdPlayer] Cannot request new ads while an ad is playing"),[2,Promise.reject(new Error("Ad already playing"))];c.label=1;case 1:return c.trys.push([1,3,,4]),s="session-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),r=30,i=parseInt(t,10),!isNaN(i)&&i>0&&(r=i),n=function(t){var r="https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(d,"/pod"),i={video:{codec:"h264",width:e.videoWidth||1280,height:e.videoHeight||720,fps:29.97,bitrate:5e3,profile:"high",pix_fmt:"yuv420p",has_b_frames:0},audio:{codec:"aac",sample_rate:48e3,bitrate:128}},n=encodeURIComponent(JSON.stringify(i));return"".concat(r,"?duration=").concat(Math.ceil(t),"&metadata=").concat(n)}(r),[4,k(n)];case 2:return(l=c.sent())?(a=l,console.log("[HlsAdPlayer] Ad parsed: ".concat(l.title,", duration: ").concat(l.duration,"s")),m(l.trackingUrls.impression),g.impression=!0,[2,Promise.resolve()]):(console.warn("[HlsAdPlayer] No ads available from VAST response"),p("ad_error"),[2,Promise.resolve()]);case 3:return u=c.sent(),console.error("[HlsAdPlayer] Error requesting ads:",u),p("ad_error"),[2,Promise.reject(u)];case 4:return[2]}})})},play:function(){return x(this,void 0,void 0,function(){var s,c,d;return D(this,function(h){if(!a)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),[2,Promise.reject(new Error("No ad loaded"))];console.log("[HlsAdPlayer] Starting ad playback");try{if(r||((f=document.createElement("video")).style.position="absolute",f.style.left="0",f.style.top="0",f.style.width="100%",f.style.height="100%",f.style.objectFit="contain",f.style.backgroundColor="#000",f.playsInline=!0,f.muted=!1,f.volume=1,console.log("[HlsAdPlayer] Created ad video element with volume ".concat(f.volume)),r=f,null==n||n.appendChild(r),T()),g={impression:g.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},s=e.volume,u=Math.max(0,Math.min(1,s||u)),(null==t?void 0:t.continueLiveStreamDuringAds)?console.log("[HlsAdPlayer] Content continues (Live mode)"):(e.pause(),console.log("[HlsAdPlayer] Content paused (VOD mode)")),console.log("[HlsAdPlayer] FORCE MUTING main video"),e.muted=!0,e.volume=0,o=!0,S(!0),r&&(c=l?0:u,r.volume=Math.max(0,Math.min(1,c)),r.muted=!1,console.log("[HlsAdPlayer] Set ad video volume to ".concat(r.volume,", muted: ").concat(r.muted,", originalMutedState: ").concat(l,", contentVolume: ").concat(s))),n&&(n.style.display="flex",n.style.pointerEvents="auto"),p("content_pause"),!(d=y(a.mediaFiles)))throw new Error("No media file available for ad");if(console.log("[HlsAdPlayer] Loading ad from: ".concat(d.url)),mu.isSupported())i&&i.destroy(),(i=new mu({enableWorker:!0,lowLatencyMode:!1})).loadSource(d.url),i.attachMedia(r),i.on(mu.Events.MANIFEST_PARSED,function(){console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),r.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),b()})}),i.on(mu.Events.ERROR,function(e,t){console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&b()});else{if(!r.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS not supported");r.src=d.url,r.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),b()})}return[2,Promise.resolve()]}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),b(),[2,Promise.reject(e)]}var f;return[2]})})},stop:function(){return x(this,void 0,void 0,function(){return D(this,function(e){return console.log("[HlsAdPlayer] Stopping ad"),o=!1,S(!1),n&&(n.style.display="none",n.style.pointerEvents="none"),i&&(i.destroy(),i=void 0),r&&(r.pause(),r.src=""),a=void 0,[2]})})},destroy:function(){var t,s;console.log("[HlsAdPlayer] Destroying"),f=!0;try{for(var d=C(v),h=d.next();!h.done;h=d.next()){var g=h.value;clearTimeout(g)}}catch(e){t={error:e}}finally{try{h&&!h.done&&(s=d.return)&&s.call(d)}finally{if(t)throw t.error}}v=[],o=!1,S(!1),e.muted=l,e.volume=l?0:u,i&&(i.destroy(),i=void 0),r&&(r.pause(),r.src="",r.remove(),r=void 0),(null==n?void 0:n.parentElement)&&n.parentElement.removeChild(n),n=void 0,a=void 0,c.clear()},isAdPlaying:function(){return o},resize:function(e,t){console.log("[HlsAdPlayer] Resizing to ".concat(e,"x").concat(t)),n&&(n.style.width="".concat(e,"px"),n.style.height="".concat(t,"px")),r&&(r.style.width="".concat(e,"px"),r.style.height="".concat(t,"px"))},on:function(e,t){c.has(e)||c.set(e,new Set),c.get(e).add(t)},off:function(e,t){var r;null===(r=c.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?u:Math.max(0,Math.min(1,t));console.log("[HlsAdPlayer] updateOriginalMutedState called: { muted: ".concat(l," -> ").concat(e,", volume: ").concat(u," -> ").concat(r," }")),l=e,u=r},getOriginalMutedState:function(){return l},getOriginalVolume:function(){return u},setAdVolume:function(e){r&&o&&(r.volume=Math.max(0,Math.min(1,e)))},getAdVolume:function(){return r&&o?r.volume:1},showPlaceholder:function(){var t;if(!n){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),n=r}n&&(n.style.display="flex",n.style.pointerEvents="auto")},hidePlaceholder:function(){n&&(n.style.display="none",n.style.pointerEvents="none")},setAllowNativeHls:function(e){0}}},e.createStormcloudPlayer=Tc,e.default=zu,e.detectBrowser=Au,e.getBrowserConfigOverrides=Iu,e.getBrowserID=Lc,e.getClientInfo=Ac,e.initializePolyfills=bu,e.isMediaStream=Zu,e.lazy=$u,e.logBrowserInfo=Lu,e.merge=ec,e.omit=Ju,e.parseQuery=function(e){var t={},r=e.split("?")[1]||"";if(!r)return t;var i=function(e){e.split("&").forEach(function(e){var r=_(e.split("="),2),i=r[0],n=r[1];if(i)try{t[decodeURIComponent(i)]=n?decodeURIComponent(n.replace(/\+/g," ")):""}catch(e){t[i]=n||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(r).forEach(function(e,r){t[r]=e}),t}catch(e){i(r)}else i(r);return t},e.players=vc,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.sendHeartbeat=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a;return D(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),[4,Lc(Ac())];case 1:return t=s.sent(),r={browserId:t,timestamp:(new Date).toISOString()},i={"Content-Type":"application/json"},e&&(i.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:i,body:JSON.stringify(r)})];case 2:if(!(n=s.sent()).ok)throw new Error("HTTP error! status: ".concat(n.status));return[4,n.json()];case 3:return s.sent(),[3,5];case 4:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending heartbeat:",a),[3,5];case 5:return[2]}})})},e.sendInitialTracking=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s;return D(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),[4,Lc(t=Ac())];case 1:return r=o.sent(),i=w({browserId:r},t),n={"Content-Type":"application/json"},e&&(n.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track",{method:"POST",headers:n,body:JSON.stringify(i)})];case 2:if(!(a=o.sent()).ok)throw new Error("HTTP error! status: ".concat(a.status));return[4,a.json()];case 3:return o.sent(),[3,5];case 4:return s=o.sent(),console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",s),[3,5];case 5:return[2]}})})},e.supportsFeature=function(e){switch(e){case"urlsearchparams":return"undefined"!=typeof URLSearchParams;case"textencoder":return"undefined"!=typeof TextEncoder;case"promises":return"undefined"!=typeof Promise;case"fetch":return"undefined"!=typeof fetch;case"crypto":return"undefined"!=typeof crypto&&void 0!==crypto.subtle;default:return!1}},e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=function(){return"undefined"!=typeof window&&"webkitSupportsPresentationMode"in document.createElement("video")},Object.defineProperty(e,"__esModule",{value:!0})});