stormcloud-video-player 0.5.22 → 0.5.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/stormcloud-vp.min.js +1 -1
- package/lib/index.cjs +112 -10
- package/lib/index.cjs.map +1 -1
- package/lib/index.js +112 -10
- package/lib/index.js.map +1 -1
- package/lib/player/StormcloudVideoPlayer.cjs +112 -10
- package/lib/player/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/players/HlsPlayer.cjs +112 -10
- package/lib/players/HlsPlayer.cjs.map +1 -1
- package/lib/players/index.cjs +112 -10
- package/lib/players/index.cjs.map +1 -1
- package/lib/sdk/prebidAdLayer.cjs +121 -3
- package/lib/sdk/prebidAdLayer.cjs.map +1 -1
- package/lib/sdk/vastParser.cjs +121 -3
- package/lib/sdk/vastParser.cjs.map +1 -1
- package/lib/ui/StormcloudVideoPlayer.cjs +112 -10
- package/lib/ui/StormcloudVideoPlayer.cjs.map +1 -1
- package/package.json +1 -1
|
@@ -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 i(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function r(e){if(Array.isArray(e))return e}function n(e,t,i){return t=c(t),g(e,h()?Reflect.construct(t,i||[],c(e).constructor):t.apply(e,i))}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,k(r.key),r)}}function o(e,t,i){return t&&s(e.prototype,t),i&&s(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(e,t,i){return(t=k(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function u(){return u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var r=y(e,t);if(r){var n=Object.getOwnPropertyDescriptor(r,t);return n.get?n.get.call(arguments.length<3?e:i):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&&m(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 m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}function p(e,t){return r(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,n,a,s,o=[],l=!0,u=!1;try{if(a=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;l=!1}else for(;!(l=(r=a.call(i)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=i.return&&(s=i.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}(e,t)||A(e,t)||v()}function y(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=c(e)););return e}function E(e,t,i,r){var n=u(c(1&r?e.prototype:e),t,i);return 2&r&&"function"==typeof n?function(e){return n.apply(i,e)}:n}function T(e){return function(e){if(Array.isArray(e))return i(e)}(e)||f(e)||A(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 k(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=typeof r)return r;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 A(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}function b(e){var i,r;function n(i,r){try{var s=e[i](r),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var r="return"===i?"return":"next";if(!o.k||t.done)return n(r,t);t=e[r](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":i.resolve({value:t,done:!0});break;case"throw":i.reject(t);break;default:i.resolve({value:t,done:!1})}(i=i.next)?n(i.key,i.arg):r=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};r?r=r.next=o:(i=r=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,i)}function i(){return function(e,t,i){if(h())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var n=new(e.bind.apply(e,r));return i&&m(n,i.prototype),n}(e,arguments,c(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),m(i,e)},L(e)}b.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},b.prototype.next=function(e){return this._invoke("next",e)},b.prototype.throw=function(e){return this._invoke("throw",e)},b.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 i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},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 i(){this.constructor=e}I(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var w=function(){return w=Object.assign||function(e){for(var t,i=1,r=arguments.length;i<r;i++)for(var n in t=arguments[i])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},w.apply(this,arguments)};function P(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]])}return i}function D(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})}function C(e,t){var i,r,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(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,r&&(n=2&o[0]?r.return:o[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,o[1])).done)return n;switch(r=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++,r=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],r=0}finally{i=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function _(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],r=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function x(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var r,n,a=i.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)s.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return s}function M(e,t,i){if(i||2===arguments.length)for(var r,n=0,a=t.length;n<a;n++)!r&&n in t||(r||(r=Array.prototype.slice.call(t,0,n)),r[n]=t[n]);return e.concat(r||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:{}},B={};var U,G={exports:{}},V={};function H(){if(U)return V;U=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),r=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 m(e,t,i){this.props=e,this.context=t,this.refs=g,this.updater=i||f}function p(){}function y(e,t,i){this.props=e,this.context=t,this.refs=g,this.updater=i||f}m.prototype.isReactComponent={},m.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")},m.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},p.prototype=m.prototype;var E=y.prototype=new p;E.constructor=y,v(E,m.prototype),E.isPureReactComponent=!0;var T=Array.isArray;function k(){}var A={H:null,A:null,T:null,S:null},b=Object.prototype.hasOwnProperty;function L(t,i,r){var n=r.ref;return{$$typeof:e,type:t,key:i,ref:void 0!==n?n:null,props:r}}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?(i=""+e.key,r={"=":"=0",":":"=2"},"$"+i.replace(/[=:]/g,function(e){return r[e]})):t.toString(36);var i,r}function P(i,r,n,a,s){var o=S(i);"undefined"!==o&&"boolean"!==o||(i=null);var l,u,d=!1;if(null===i)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(i.$$typeof){case e:case t:d=!0;break;case c:return P((d=i._init)(i._payload),r,n,a,s)}}if(d)return s=s(i),d=""===a?"."+w(i,0):a,T(s)?(n="",null!=d&&(n=d.replace(R,"$&/")+"/"),P(s,r,n,"",function(e){return e})):null!=s&&(I(s)&&(l=s,u=n+(null==s.key||i&&i.key===s.key?"":(""+s.key).replace(R,"$&/")+"/")+d,s=L(l.type,u,l.props)),r.push(s)),1;d=0;var f,v=""===a?".":a+":";if(T(i))for(var g=0;g<i.length;g++)d+=P(a=i[g],r,n,o=v+w(a,g),s);else if("function"==typeof(g=null===(f=i)||"object"!==S(f)?null:"function"==typeof(f=h&&f[h]||f["@@iterator"])?f:null))for(i=g.call(i),g=0;!(a=i.next()).done;)d+=P(a=a.value,r,n,o=v+w(a,g++),s);else if("object"===o){if("function"==typeof i.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(k,k):(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}(i),r,n,a,s);throw r=String(i),Error("Objects are not valid as a React child (found: "+("[object Object]"===r?"object with keys {"+Object.keys(i).join(", ")+"}":r)+"). If you meant to render a collection of children, use an array instead.")}return d}function D(e,t,i){if(null==e)return e;var r=[],n=0;return P(e,r,"","",function(e){return t.call(i,e,n++)}),r}function C(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 _="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)},x={map:D,forEach:function(e,t,i){D(e,function(){t.apply(this,arguments)},i)},count:function(e){var t=0;return D(e,function(){t++}),t},toArray:function(e){return D(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 V.Activity=d,V.Children=x,V.Component=m,V.Fragment=i,V.Profiler=n,V.PureComponent=y,V.StrictMode=r,V.Suspense=l,V.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,V.__COMPILER_RUNTIME={__proto__:null,c:function(e){return A.H.useMemoCache(e)}},V.cache=function(e){return function(){return e.apply(null,arguments)}},V.cacheSignal=function(){return null},V.cloneElement=function(e,t,i){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var r=v({},e.props),n=e.key;if(null!=t)for(a in void 0!==t.key&&(n=""+t.key),t)!b.call(t,a)||"key"===a||"__self"===a||"__source"===a||"ref"===a&&void 0===t.ref||(r[a]=t[a]);var a=arguments.length-2;if(1===a)r.children=i;else if(1<a){for(var s=Array(a),o=0;o<a;o++)s[o]=arguments[o+2];r.children=s}return L(e.type,n,r)},V.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},V.createElement=function(e,t,i){var r,n={},a=null;if(null!=t)for(r in void 0!==t.key&&(a=""+t.key),t)b.call(t,r)&&"key"!==r&&"__self"!==r&&"__source"!==r&&(n[r]=t[r]);var s=arguments.length-2;if(1===s)n.children=i;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(r in s=e.defaultProps)void 0===n[r]&&(n[r]=s[r]);return L(e,a,n)},V.createRef=function(){return{current:null}},V.forwardRef=function(e){return{$$typeof:o,render:e}},V.isValidElement=I,V.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:C}},V.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},V.startTransition=function(e){var t=A.T,i={};A.T=i;try{var r=e(),n=A.S;null!==n&&n(i,r),"object"===S(r)&&null!==r&&"function"==typeof r.then&&r.then(k,_)}catch(e){_(e)}finally{null!==t&&null!==i.types&&(t.types=i.types),A.T=t}},V.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},V.use=function(e){return A.H.use(e)},V.useActionState=function(e,t,i){return A.H.useActionState(e,t,i)},V.useCallback=function(e,t){return A.H.useCallback(e,t)},V.useContext=function(e){return A.H.useContext(e)},V.useDebugValue=function(){},V.useDeferredValue=function(e,t){return A.H.useDeferredValue(e,t)},V.useEffect=function(e,t){return A.H.useEffect(e,t)},V.useEffectEvent=function(e){return A.H.useEffectEvent(e)},V.useId=function(){return A.H.useId()},V.useImperativeHandle=function(e,t,i){return A.H.useImperativeHandle(e,t,i)},V.useInsertionEffect=function(e,t){return A.H.useInsertionEffect(e,t)},V.useLayoutEffect=function(e,t){return A.H.useLayoutEffect(e,t)},V.useMemo=function(e,t){return A.H.useMemo(e,t)},V.useOptimistic=function(e,t){return A.H.useOptimistic(e,t)},V.useReducer=function(e,t,i){return A.H.useReducer(e,t,i)},V.useRef=function(e){return A.H.useRef(e)},V.useState=function(e){return A.H.useState(e)},V.useSyncExternalStore=function(e,t,i){return A.H.useSyncExternalStore(e,t,i)},V.useTransition=function(){return A.H.useTransition()},V.version="19.2.4",V}var K;G.exports;function j(){return K||(K=1,G.exports=H()),G.exports}var W;N.exports;var q=(W||(W=1,N.exports=function(){if(F)return B;F=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(t,i,r){var n=null;if(void 0!==r&&(n=""+r),void 0!==i.key&&(n=""+i.key),"key"in i)for(var a in r={},i)"key"!==a&&(r[a]=i[a]);else r=i;return i=r.ref,{$$typeof:e,type:t,key:n,ref:void 0!==i?i:null,props:r}}return B.Fragment=t,B.jsx=i,B.jsxs=i,B}()),N.exports),Y=j(),z=O(Y),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",ie="level",re="audioTrack",ne="subtitleTrack",ae="main",se="audio",oe="subtitle",le=function(){return o(function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=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_=i,this.totalWeight_=r},[{key:"sample",value:function(e,t){var i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*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,i,r){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_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new le(t),this.fast_=new le(i),this.defaultTTFB_=n,this.ttfb_=new le(t)},[{key:"update",value:function(e,t){var i=this.slow_,r=this.fast_,n=this.ttfb_;i.halfLife!==e&&(this.slow_=new le(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new le(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new le(e,n.getEstimate(),n.getTotalWeight()))}},{key:"sample",value:function(e,t){var i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}},{key:"sampleTTFB",value:function(e){var t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,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,i){return(t=function(e){var t=function(e,t){if("object"!=S(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=S(r))return r;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:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function de(){return de=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},de.apply(null,arguments)}function he(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function fe(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?he(Object(i),!0).forEach(function(t){ce(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):he(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}var ve=o(function e(t,i){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 r="[".concat(t,"]:");this.trace=ge,this.debug=i.debug.bind(null,r),this.log=i.log.bind(null,r),this.warn=i.warn.bind(null,r),this.info=i.info.bind(null,r),this.error=i.error.bind(null,r)}),ge=function(){},me={trace:ge,debug:ge,log:ge,warn:ge,info:ge,error:ge};function pe(){return de({},me)}function ye(e,t,i){return t[e]?t[e].bind(t):function(e,t){var i=self.console[e];return i?i.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):ge}(e,i)}var Ee=pe();var Te=Ee;function ke(){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 i=Object.keys(e),r=Object.keys(t),n=i.length,a=r.length;return!n||!a||n===a&&!i.some(function(e){return-1===r.indexOf(e)})}function Ae(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if("undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(e);if(t){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.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 be(e){for(var t="",i=0;i<e.length;i++){var r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}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,i,r,n,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.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 r.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=i.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=r.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(we)),we.exports),De=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}}),Ce="audio",_e="video",xe="audiovideo",Me=function(){return o(function e(t){var i,r,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=Be(i=this,r="stats"))&&(n.enumerable=!0,Object.defineProperty(i,r,n))},[{key:"setByteRange",value:function(e,t){var i,r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}},{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({},Ce,null),_e,null),xe,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 De),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[Ce]=null,e[_e]=null,e[xe]=null}}])}();function Oe(e){return"initSegment"!==e.sn}var Fe=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[i]))._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=e,r}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],i=this.byteRange[1];if(X(t)&&X(i))return i-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 i=Object.keys(t);if(1===i.length){var r=this._decryptdata=t[i[0]]||null;r&&(this._decryptdata=r.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,i=Object.keys(this.levelkeys),r=i.length;if(r>1||1===r&&null!=(t=this.levelkeys[i[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 i,r=t[e];!r||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=r.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,i,r,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,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a}}}])}(Me),Ne=function(e){function t(e,i,r,s,o){var l;a(this,t),(l=n(this,t,[r])).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=i,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 Be(e,t){var i=Object.getPrototypeOf(e);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r||Be(i,t)}}var Ue=Math.pow(2,32)-1,Ge=[].push,Ve={video:1,audio:2,id3:3,text:4};function He(e){return String.fromCharCode.apply(null,e)}function Ke(e,t){var i=e[t]<<8|e[t+1];return i<0?65536+i:i}function je(e,t){var i=qe(e,t);return i<0?4294967296+i:i}function We(e,t){var i=je(e,t);return i*=Math.pow(2,32),i+=je(e,t+4)}function qe(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Ye(e,t){var i=[];if(!t.length)return i;for(var r=e.byteLength,n=0;n<r;){var a=je(e,n),s=a>1?n+a:r;if(He(e.subarray(n+4,n+8))===t[0])if(1===t.length)i.push(e.subarray(n+8,s));else{var o=Ye(e.subarray(n+8,s),t.slice(1));o.length&&Ge.apply(i,o)}n=s}return i}function ze(e){var t=[],i=e[0],r=8,n=je(e,r);r+=4;var a=0,s=0;0===i?(a=je(e,r),s=je(e,r+4),r+=8):(a=We(e,r),s=We(e,r+8),r+=16),r+=2;var o=e.length+s,l=Ke(e,r);r+=2;for(var u=0;u<l;u++){var c=r,d=je(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return Te.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,r=c+=4}return{earliestPresentationTime:a,timescale:n,version:i,referencesCount:l,references:t}}function Xe(e){for(var t=[],i=Ye(e,["moov","trak"]),r=0;r<i.length;r++){var n=i[r],a=Ye(n,["tkhd"])[0];if(a){var s=a[0],o=je(a,0===s?12:20),l=Ye(n,["mdia","mdhd"])[0];if(l){var u=je(l,0===(s=l[0])?12:20),c=Ye(n,["mdia","hdlr"])[0];if(c){var d=He(c.subarray(8,12)),h={soun:Ce,vide:_e}[d],f=Qe(Ye(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 Ye(e,["moov","mvex","trex"]).forEach(function(e){var i=je(e,4),r=t[i];r&&(r.default={duration:je(e,12),flags:je(e,20)})}),t}function Qe(e){var t,i=e.subarray(8),r=i.subarray(86),n=He(i.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=Ye(i,[n])[0];Ye(o.subarray("enca"===n?28:78),["sinf"]).forEach(function(e){var t=Ye(e,["schm"])[0];if(t){var i=He(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=Ye(e,["frma"])[0];r&&(a=He(r))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=Ye(r,["avcC"])[0];u&&u.length>3&&(a+="."+Ze(u[1])+Ze(u[2])+Ze(u[3]),t=$e("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var c=Ye(i,[n])[0],d=Ye(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++],m=(248&g)>>3;31===m&&(m+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+m}break;case"hvc1":case"hev1":var p=Ye(r,["hvcC"])[0];if(p&&p.length>12){var y=p[1],E=["","A","B","C"][y>>6],T=31&y,k=je(p,2),S=(32&y)>>5?"H":"L",A=p[12],b=p.subarray(6,12);a+="."+E+T,a+="."+function(e){for(var t=0,i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}(k).toString(16).toUpperCase(),a+="."+S+A;for(var L="",I=b.length;I--;){var R=b[I];if(R||L)L="."+R.toString(16).toUpperCase()+L}a+=L}t=$e("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=$e(a,r)||a;break;case"vp09":var w=Ye(r,["vpcC"])[0];if(w&&w.length>6){var P=w[4],D=w[5],C=w[6]>>4&15;a+="."+et(P)+"."+et(D)+"."+et(C)}break;case"av01":var _=Ye(r,["av1C"])[0];if(_&&_.length>2){var x=_[1]>>>5,M=31&_[1],O=_[2]>>>7?"H":"M",F=(64&_[2])>>6,N=(32&_[2])>>5,B=2===x&&F?N?12:10:F?10:8,U=(16&_[2])>>4,G=(8&_[2])>>3,V=(4&_[2])>>2,H=3&_[2];a+="."+x+"."+et(M)+O+"."+et(B)+"."+U+"."+G+V+H+"."+et(1)+"."+et(1)+"."+et(1)+".0",t=$e("dav1",r)}}return{codec:a,encrypted:s,supplemental:t}}function $e(e,t){var i=Ye(t,["dvvC"]),r=i.length?i[0]:Ye(t,["dvcC"])[0];if(r){var n=r[2]>>1&127,a=r[2]<<5&32|r[3]>>3&31;return e+"."+et(n)+"."+et(a)}}function Je(e,t){for(var i=t+5;128&e[t++]&&t<i;);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){Ye(e,["moov","trak"]).forEach(function(e){var i=Ye(e,["mdia","minf","stbl","stsd"])[0];if(i){var r=i.subarray(8),n=Ye(r,["enca"]),a=n.length>0;a||(n=Ye(r,["encv"])),n.forEach(function(e){Ye(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var i=it(e);i&&t(i,a)})})}})}function it(e){var t=Ye(e,["schm"])[0];if(t){var i=He(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=Ye(e,["schi","tenc"])[0];if(r)return r}}}function rt(e,t){var i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function nt(e,t){var i=[],r=t.samples,n=t.timescale,a=t.id,s=!1;return Ye(r,["moof"]).map(function(o){var l=o.byteOffset-8;Ye(o,["traf"]).map(function(o){var u=Ye(o,["tfdt"]).map(function(e){var t=e[0],i=je(e,4);return 1===t&&(i*=Math.pow(2,32),i+=je(e,8)),i/n})[0];return void 0!==u&&(e=u),Ye(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),m=8;c===a&&(!!(1&d)&&(m+=8),!!(2&d)&&(m+=4),!!(8&d)&&(h=je(u,m),m+=4),f&&(v=je(u,m),m+=4),g&&(m+=4),"video"===t.type&&(s=at(t.codec)),Ye(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),m=0,p=!!(512&u),y=0,E=!!(1024&u),T=!!(2048&u),k=0,S=je(a,4),A=8;c&&(d=je(a,A),A+=4),f&&(A+=4);for(var b=d+l,L=0;L<S;L++){if(g?(m=je(a,A),A+=4):m=h,p?(y=je(a,A),A+=4):y=v,E&&(A+=4),T&&(k=0===o?je(a,A):qe(a,A),A+=4),t.type===_e)for(var I=0;I<y;){var R=je(r,b);if(st(s,r[b+=4]))ot(r.subarray(b,b+R),s?2:1,e+k/n,i);b+=R,I+=R+4}e+=m/n}}))})})}),i}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 i=t>>1&63;return 39===i||40===i}return 6===(31&t)}function ot(e,t,i,r){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){Te.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,m=g?2+3*(31&v):0,p=new Uint8Array(m);if(g){p[0]=v;for(var y=1;y<m;y++)p[y]=n[c++]}r.push({type:f,payloadType:s,pts:i,bytes:p})}}}}}else if(5===s&&o>16){for(var E=[],T=0;T<16;T++){var k=n[c++].toString(16);E.push(1==k.length?"0"+k:k),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var S=o-16,A=new Uint8Array(S),b=0;b<S;b++)A[b]=n[c++];r.push({payloadType:s,pts:i,uuid:E.join(""),userData:Ae(A),userDataBytes:A})}}}function lt(e){for(var t=e.byteLength,i=[],r=1;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;var n=t-i.length,a=new Uint8Array(n),s=0;for(r=0;r<n;s++,r++)s===i[0]&&(s++,i.shift()),a[r]=e[s];return a}function ut(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");var r,n;r=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var n=i.length,a=8,s=n;s--;)a+=i[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(i[s],a),a+=i[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,i)}function ct(e){var t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:i,size:t};var a=e.buffer,s=be(new Uint8Array(a,i+12,16)),o=null,l=0;if(0===n)l=28;else{var u=e.getUint32(28);if(!u||r<32+16*u)return{offset:i,size:t};o=[];for(var c=0;c<u;c++)o.push(new Uint8Array(a,i+32+16*c,16));l=32+16*u}if(!l)return{offset:i,size:t};var d=e.getUint32(l);return t-32<d?{offset:i,size:t}:{version:n,systemId:s,kids:o,data:new Uint8Array(a,i+l+4,d),offset:i,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 i=ht[t];return!!i&&!!i[e.slice(0,4)]}function vt(e,t){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!gt(e,t,i)})}function gt(e,t){var i,r=ke(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(i=null==r?void 0:r.isTypeSupported(mt(e,t)))&&i}function mt(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function pt(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,i){var r=t&&at(i)?9:ht.video[i];return r?(2*r+e)/(e?3:2):(ht.audio[i]+e)/(e?2:1)},0)}var Et={};var Tt=/flac|opus|mp4a\.40\.34/i;function kt(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(Tt,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(Et[e])return Et[e];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],r=0;r<i.length;r++){var n;if(gt(i[r],"audio",t))return Et[e]=i[r],i[r];if("mp3"===i[r]&&null!=(n=ke(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))&&(At(e,"audio")||At(e,"video")))return e;if(t){var i=t.split(",");if(i.length>1){if(e)for(var r=i.length;r--;)if(i[r].substring(0,4)===e.substring(0,4))return i[r];return i[0]}}return t||e}function At(e,t){return ft(e,t)&>(e,t)}function bt(e){if(e.startsWith("av01.")){for(var t=e.split("."),i=["0","111","01","01","01","0"],r=t.length;r>4&&r<10;r++)t[r]=i[r-4];return t.join(".")}return e}function Lt(e){var t=ke(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 Dt(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.videoCodec;if(!n&&!e.audioCodec||!i)return Promise.resolve(wt);for(var a=[],s=function(e){var t,i=null==(t=e.videoCodec)?void 0:t.split(","),r=_t(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map(function(e){var t={contentType:mt(bt(e),"video"),width:n,height:a,bitrate:r,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,i){var r,n=null==(r=e.audioCodec)?void 0:r.split(","),a=_t(e);if(n&&e.audioGroups)return e.audioGroups.reduce(function(e,r){var s,o=r?null==(s=t.groups[r])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===r){var s=parseFloat(t.channels||"");n.forEach(function(t){var r={contentType:mt(t,"audio"),bitrate:i?Ct(t,a):a};s&&(r.channels=""+s),e.push(r)})}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="",i=e.audio,r=e.video;if(r){var n=It(r.contentType);t+="".concat(n,"_r").concat(r.height,"x").concat(r.width,"f").concat(Math.ceil(r.framerate)).concat(r.transferFunction||"sd","_").concat(Math.ceil(r.bitrate/1e5))}if(i){var a=It(i.contentType);t+="".concat(r?"_":"").concat(a,"_c").concat(i.channels)}return t}(e);return r[t]||(r[t]=i.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 Ct(e,t){if(t<=1)return 1;var i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function _t(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var xt=["NONE","TYPE-0","TYPE-1",null];var Mt=["SDR","PQ","HLG"];var Ot="",Ft="YES",Nt="v2";function Bt(e){var t=e.canSkipUntil,i=e.canSkipDateRanges,r=e.age;return t&&r<t/2?i?Nt:Ft:Ot}var Ut=function(){return o(function e(t,i,r){a(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=i,this.skip=r},[{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 i;this.supplemental=t.supplemental;var r=null==(i=t.supplemental)?void 0:i.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=",".concat(r.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 Vt(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return Vt(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 i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(t)&&i.push(t)}else if("text"===e){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(t)&&r.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 Vt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Ht(e,t){var i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){var n="SDR"!==(r=t.allowedVideoRanges||Mt.slice(0)).join("")&&!t.videoCodec;(i=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}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}var Kt=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(i,r){if(e&&(r=e(i,r)),"object"===S(r)&&null!==r){if(t.has(r))return;t.add(r)}return r}}(t))};function jt(e,t){Te.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function Wt(e){return e.reduce(function(e,t){var i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);var r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function qt(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function Yt(e,t,i){if("attrs"in e){var r=t.indexOf(e);if(-1!==r)return r}for(var n=0;n<t.length;n++){if(zt(e,t[n],i))return n}return-1}function zt(e,t,i){var r=e.groupId,n=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===r||t.groupId===r)&&(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]:"",i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some(function(e){return-1===r.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function Xt(e,t){var i=e.audioCodec,r=e.channels;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function Qt(e,t,i){for(var r=t;r>-1;r--)if(i(e[r]))return r;for(var n=t+1;n<e.length;n++)if(i(e[n]))return n;return-1}function $t(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}var Jt=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["abr",e.logger])).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.supportedCache={},i.bwEstimator=void 0,i._abandonRulesCheck=function(e){var t,r=i,n=r.fragCurrent,a=r.partCurrent,s=r.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=i._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var m=g>-1&&g!==v,p=!!e||m;if(p||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(p||null!==y){var E=i.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(!(h<=Math.max(E,d/(2*T)*1e3))){var k=y?y.len/T:0,S=c.loading.first?c.loading.first-c.loading.start:-1,A=c.loaded&&S>-1,b=i.getBwEstimate(),L=s.levels,I=L[v],R=Math.max(c.loaded,Math.round(d*(n.bitrate||I.averageBitrate)/8)),w=A?h-S:h;w<1&&A&&(w=Math.min(h,8*c.loaded/b));var P=A?1e3*c.loaded/w:0,D=E/1e3,C=P?(R-c.loaded)/P:8*R/b+D;if(!(C<=k)){var _,x=P?8*P:b,M=!0===(null==(t=(null==e?void 0:e.details)||i.hls.latestLevelDetails)?void 0:t.live),O=i.hls.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(_=v-1;_>f;_--){var N=L[_].maxBitrate,B=!L[_].details||M;if((F=i.getTimeToLoadFrag(D,x,d*N,B))<Math.min(k,d+D))break}if(!(F>=C||F>10*d)){A?i.bwEstimator.sample(h-Math.min(E,S),c.loaded):i.bwEstimator.sampleTTFB(h);var U=L[_].maxBitrate;i.getBwEstimate()*O>U&&i.resetEstimator(U);var G=i.findBestLevel(U,f,_,0,k,1,1);G>-1&&(_=G),i.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(k.toFixed(3)," s\n Estimated load time for current fragment: ").concat(C.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(b)?0|b:"Unknown"," bps\n New BW estimate: ").concat(0|i.getBwEstimate()," bps\n Switching to level ").concat(_," @ ").concat(0|U," bps")),s.nextLoadLevel=s.nextAutoLevel=_,i.clearTimer();var V=function(){if(i.clearTimer(),i.fragCurrent===n&&i.hls.loadLevel===_&&_>0){var e=i.getStarvationDelay();if(i.warn("Aborting inflight request ".concat(_>0?"and switching down":"","\n Fragment duration: ").concat(n.duration.toFixed(3)," s\n Time to underbuffer: ").concat(e.toFixed(3)," s")),n.abortRequests(),i.fragCurrent=i.partCurrent=null,_>f){var t=i.findBestLevel(i.hls.levels[f].bitrate,f,_,0,e,1,1);-1===t&&(t=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=t,i.resetEstimator(i.hls.levels[t].bitrate)}}};m||C>2*F?V():i.timer=self.setInterval(V,1e3*F),s.trigger(ee.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:c})}}}}}}}},i.hls=e,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}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 i=t.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r: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 i=t.frag,r=this.fragCurrent,n=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var a=performance.now(),s=n?n.stats:i.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,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var i=this.hls.config,r=t.stats.loading,n=r.end-r.first;X(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var i=t.frag,r=t.part,n=r?r.stats:i.stats;if(i.type===ae&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var a=r?r.duration:i.duration,s=this.hls.levels[i.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(i.bitrateTest){var u={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(ee.FRAG_BUFFERED,u),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}},{key:"onFragBuffered",value:function(e,t){var i=t.frag,r=t.part,n=null!=r&&r.stats.loaded?r.stats:i.stats;if(!n.aborted&&!this.ignoreFragment(i)){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(),i.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,i=e.minAutoLevel,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(r,i,t,0,n,1,1);if(a>-1)return a;var s=this.hls.firstLevel,o=Math.min(Math.max(s,i),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(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},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,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,n=i.config,a=i.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,r,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,r,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=i.levels[a],m=i.loadLevelObj;return m&&(null==g?void 0:g.bitrate)<m.bitrate?a:i.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=e.media;if(!t)return 1/0;var i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}},{key:"getBwEstimate",value:function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}},{key:"findBestLevel",value:function(e,t,i,r,n,a,s){var o,l=this,u=r+n,c=this.lastLoadedFragLevel,d=-1===c?this.hls.firstLevel:c,h=this.fragCurrent,f=this.partCurrent,v=this.hls,g=v.levels,m=v.allAudioTracks,p=v.loadLevel,y=v.config;if(1===g.length)return 0;var E,T=g[d],k=!(null==(o=this.hls.latestLevelDetails)||!o.live),S=-1===p||-1===c,A="SDR",b=(null==T?void 0:T.frameRate)||0,L=y.audioPreference,I=y.videoPreference,R=this.audioTracksByGroup||(this.audioTracksByGroup=Wt(m)),w=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;var P=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce(function(e,i,r){if(!i.codecSet)return e;var n=i.audioGroups,a=e[i.codecSet];a||(e[i.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,i.bitrate);var s=Math.min(i.height,i.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,i.frameRate),a.minIndex=Math.min(a.minIndex,r),a.maxScore=Math.max(a.maxScore,i.score),a.fragmentError+=i.fragmentError,a.videoRanges[i.videoRange]=(a.videoRanges[i.videoRange]||0)+1,n&&n.forEach(function(e){if(e){var i=t.groups[e];i&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+i.channels[e]}))}}),e},{})}(g,R,t,i)),D=function(e,t,i,r,n){for(var a=Object.keys(e),s=null==r?void 0:r.channels,o=null==r?void 0:r.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,m=0,p=[],y=Ht(t,n),E=y.preferHDR,T=y.allowedVideoRanges,k=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),T.filter(function(e){return t.videoRanges[e]>0}).length>0&&(d=!0)},S=a.length;S--;)k();h=X(h)?h:0,f=X(f)?f:0;var A=Math.max(1080,h),b=Math.max(30,f);v=X(v)?v:i,i=Math.max(v,i),d||(t=void 0);var L=a.length>1;return{codecSet:a.reduce(function(t,r){var n=e[r];if(r===t)return t;if(p=d?T.filter(function(e){return n.videoRanges[e]>0}):[],L){if(n.minBitrate>i)return jt(r,"min bitrate of ".concat(n.minBitrate," > current estimate of ").concat(i)),t;if(!n.hasDefaultAudio)return jt(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return jt(r,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!n.channels[s])return jt(r,"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(r,"no renditions with stereo sound found"),t;if(n.minHeight>A)return jt(r,"min resolution of ".concat(n.minHeight," > maximum of ").concat(A)),t;if(n.minFramerate>b)return jt(r,"min framerate of ".concat(n.minFramerate," > maximum of ").concat(b)),t;if(!p.some(function(e){return n.videoRanges[e]>0}))return jt(r,"no variants with VIDEO-RANGE of ".concat(Kt(p)," found")),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return jt(r,'video codec preference "'.concat(l,'" not found')),t;if(n.maxScore<m)return jt(r,"max score of ".concat(n.maxScore," < selected max of ").concat(m)),t}return t&&(yt(r)>=yt(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,m=n.maxScore,r)},void 0),videoRanges:p,preferHDR:E,minFramerate:f,minBitrate:v,minIndex:g}}(P,A,e,L,I),C=D.codecSet,_=D.videoRanges,x=D.minFramerate,M=D.minBitrate,O=D.minIndex,F=D.preferHDR;w=O,E=C,A=F?_[_.length-1]:_[0],b=x,e=Math.max(e,M),this.log("picked start tier ".concat(Kt(D)))}else E=null==T?void 0:T.codecSet,A=null==T?void 0:T.videoRange;for(var N,B,U=f?f.duration:h?h.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,V=[],H=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,i,r,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,i){if(i){var r=t.groups[i];if(!r)throw new Error("Audio track group ".concat(i," not found"));Object.keys(r.channels).forEach(function(t){e[t]=(e[t]||0)+r.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(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(n,8e6))||!!d&&X(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,R,A,b,e,L)?(t.supportedPromise=Dt(t,R,h,l.supportedCache),t.supportedPromise.then(function(e){if(l.hls){t.supportedResult=e;var i=l.hls.levels,r=i.indexOf(t);e.error?l.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(r," ").concat(Kt(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&l.log("MediaCapabilities decodingInfo for level ".concat(r," not smooth or powerEfficient: ").concat(Kt(e))):(l.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(r," ").concat(Kt(e))),r>-1&&i.length>1&&(l.log("Removing unsupported level ".concat(r)),l.hls.removeLevel(r),-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||A&&t.videoRange!==A||o&&b>t.frameRate||!o&&b>0&&b<t.frameRate||null!=(N=t.supportedResult)&&null!=(N=N.decodingInfoResults)&&N.some(function(e){return!1===e.smooth}))&&(!S||K!==w))return V.push(K),0;var v,m=t.details,T=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||U;v=o?s*e:a*e;var I=U&&r>=2*U&&0===n?t.averageBitrate:t.maxBitrate,P=l.getTimeToLoadFrag(G,v,I*T,void 0===m);if(v>=I&&(K===c||0===t.loadError&&0===t.fragmentError)&&(P<=G||!X(P)||k&&!l.bitrateTestDelay||P<u)){var D=l.forcedAutoLevel;return K===p||-1!==D&&D===p||(V.length&&l.trace("Skipped level(s) ".concat(V.join(",")," of ").concat(i,' max with CODECS and VIDEO-RANGE:"').concat(g[V[0]].codecs,'" ').concat(g[V[0]].videoRange,'; not compatible with "').concat(E,'" ').concat(A)),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(T.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(p))),S&&(l.firstSelection=K),{v:K}}},K=i;K>=t;K--)if(0!==(B=H())&&B)return B.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){var t=this.hls,i=t.maxAutoLevel,r=t.minAutoLevel;return Math.min(Math.max(e,r),i)}}])}(ve),Zt=function(e,t){for(var i=0,r=e.length-1,n=null,a=null;i<=r;){var s=t(a=e[n=(i+r)/2|0]);if(s>0)i=n+1;else{if(!(s<0))return a;r=n-1}}return null};function ei(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=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-i;s>0&&s<15e-7&&(i+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===ti(i,r,a)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var r=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},i);return e.start<=r}return!1}(a,e,Math.min(n,r))))return a;var o=Zt(t,ti.bind(null,i,r));return!o||o===e&&a?a:o}function ti(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(i.start<=e&&i.start+i.duration>e)return 0;var r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function ii(e,t,i){var r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function ri(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){var r,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:(r=e,e.end<=i?1:e.start>i?-1:0)}),r||null}return null}function ni(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 ai(e){return e.details.startsWith("key")}function si(e){return ai(e)&&!!e.frag&&!e.frag.decryptdata}function oi(e,t){var i=ni(t);return e.default["".concat(i?"timeout":"error","Retry")]}function li(e,t){var i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function ui(e){return fe(fe({},e),{errorRetry:null,timeoutRetry:null})}function ci(e,t,i,r){if(!e)return!1;var n=null==r?void 0:r.code,a=t<e.maxNumRetry&&(function(e){return di(e)||!!e&&(e<400||e>499)}(n)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,a):a}function di(e){return 0===e&&!1===navigator.onLine}var hi=0,fi=2,vi=3,gi=5,mi=0,pi=1,yi=2,Ei=4,Ti=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["error-controller",e.logger])).hls=void 0,i.playlistError=0,i.hls=e,i.registerListeners(),i}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,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}},{key:"variantHasKey",value:function(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;var r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(function(e){return r.indexOf(e.groupId)>=0}).some(function(e){var i;return null==(i=e.details)?void 0:i.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 i;if(!t.fatal){var r=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!=(i=t.frag)&&i.gap)return void(t.errorAction=ki());case Z.FRAG_GAP:case Z.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=fi);case Z.LEVEL_EMPTY_ERROR:case Z.LEVEL_PARSING_ERROR:var a,s=t.parent===ae?t.level:r.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=r.loadLevelObj;if(o&&(n.type===re&&o.hasAudioGroup(n.groupId)||n.type===ne&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=fi,void(t.errorAction.flags=pi)}return;case Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:fi,flags:yi});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:fi,flags:Ei});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:r.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=ki())}t.type===J.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ki())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var i=oi(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(ci(i,r,ni(e),e.response))return{action:gi,flags:mi,retryConfig:i,retryCount:r};var n=this.getLevelSwitchAction(e,t);return i&&(n.retryConfig=i,n.retryCount=r),n}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=oi(ai(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(r&&(e.details!==Z.FRAG_GAP&&r.fragmentError++,!si(e)&&ci(o,l,ni(e),e.response)))return{action:gi,flags:mi,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,i);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var i=this.hls;null==t&&(t=i.loadLevel);var r=this.hls.levels[t];if(r){var n,a,s=e.details;r.loadError++,s===Z.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,u=i.loadLevel,c=i.minAutoLevel,d=i.maxAutoLevel;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);for(var h,f,v,g=null==(n=e.frag)?void 0:n.type,m=(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 r.audioCodec!==t}),p="video"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR)&&l.some(function(e){var t=e.codecSet,i=e.audioCodec;return r.codecSet!==t&&r.audioCodec===i}),y=null!=(a=e.context)?a:{},E=y.type,T=y.groupId,k=function(){var t=(S+u)%l.length;if(t!==u&&t>=c&&t<=d&&0===l[t].loadError){var i=l[t];if(s===Z.FRAG_GAP&&g===ae&&e.frag){var n=l[t].details;if(n){var a=ei(e.frag,n.fragments,e.frag.start);if(null!=a&&a.gap)return 0}}else{if(E===re&&i.hasAudioGroup(T)||E===ne&&i.hasSubtitleGroup(T))return 0;if(g===se&&null!=(h=r.audioGroups)&&h.some(function(e){return i.hasAudioGroup(e)})||g===oe&&null!=(f=r.subtitleGroups)&&f.some(function(e){return i.hasSubtitleGroup(e)})||m&&r.audioCodec===i.audioCodec||p&&r.codecSet===i.codecSet||!m&&r.codecSet!==i.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(v=k())||1!==v););if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:fi,flags:mi,nextAutoLevel:o}}return{action:fi,flags:pi}}},{key:"onErrorOut",value:function(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case hi:break;case fi: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,i=e.errorAction;if(i){var r=i.flags,n=i.nextAutoLevel;switch(r){case mi:this.switchLevel(e,n);break;case yi:var a=this.getVariantLevelIndex(e.frag),s=t.levels[a],o=null==s?void 0:s.attrs["HDCP-LEVEL"];if(i.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=xt[xt.indexOf(o)-1],i.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'));break}case Ei: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(be(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)i.resolved=!0;else if(v&&v.type!==ae){var g=v.decryptdata;g&&!l.matches(g)&&(i.resolved=!0)}}}i.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 i=It(e.mimeType),r=this.hls.levels,n=r.length;n--;)r[n]["".concat(e.sourceBufferName,"Codec")]===i&&(this.log("Removing level ".concat(n," for ").concat(e.details,' ("').concat(i,'" not supported)')),this.hls.removeLevel(n))}}])}(ve);function ki(e){var t={action:hi,flags:mi};return e&&(t.resolved=!0),t}var Si="NOT_LOADED",Ai="APPENDING",bi="PARTIAL",Li="OK",Ii=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 i=this.activePartLists[t];if(i)for(var r=i.length;r--;){var n=i[r];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,i){for(var r=this.fragments,n=Object.keys(r),a=n.length;a--;){var s=r[n[a]];if((null==s?void 0:s.body.type)===t&&(!i||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,i,r,n){var a=this;this.timeRanges&&(this.timeRanges[e]=t);var s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(r){var o=a.fragments[r];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 i=!a.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&a.removeFragment(o.body),i}):a.removeFragment(o.body))}else o.body.type===i&&a.removeFragment(o.body)})}},{key:"detectPartialFragments",value:function(e){var t=this,i=this.timeRanges;if(i&&"initSegment"!==e.frag.sn){var r=e.frag,n=wi(r),a=this.fragments[n];if(!(!a||a.buffered&&r.gap)){var s=!r.relurl;Object.keys(i).forEach(function(n){var o=r.elementaryStreams[n];if(o){var l=i[n],u=s||!0===o.partial;a.range[n]=t.getBufferedTimes(r,e.part,u,l)}}),a.loaded=null,Object.keys(a.range).length?(this.bufferedEnd(a,r),Ri(a)||this.removeParts(r.sn-1,r.type)):this.removeFragment(a.body)}}}},{key:"bufferedEnd",value:function(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}},{key:"removeParts",value:function(e,t){var i=this.activePartLists[t];i&&(this.activePartLists[t]=Pi(i,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var i=wi(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}},{key:"getBufferedTimes",value:function(e,t,i,r){for(var n={time:[],partial:i},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<r.length;u++){var c=r.start(u)-this.bufferPadding,d=r.end(u)+this.bufferPadding;if(l>=c&&o<=d){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(s,r.end(u))});break}if(a<d&&s>c){var h=Math.max(a,r.start(u)),f=Math.min(s,r.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,i,r,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&Ri(u)&&(i=u.body.start-s,r=u.body.end+s,e>=i&&e<=r&&(t=Math.min(e-i,r-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||Ri(t))}},{key:"getState",value:function(e){var t=wi(e),i=this.fragments[t];return i?i.buffered?Ri(i)?bi:Li:Ai:Si}},{key:"isTimeBuffered",value:function(e,t,i){for(var r,n,a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)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 i=t.frag,r=t.part?null:t,n=wi(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var i=t.frag,r=t.part,n=t.timeRanges,a=t.type;if("initSegment"!==i.sn){var s=i.type;if(r){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(r)}this.timeRanges=n;var l=n[a];this.detectEvictedFragments(a,l,s,r)}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=wi(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,i=Object.keys(t);if(!e)return i.length>0;for(var r=i.length;r--;){var n=t[i[r]];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,i,r,n){var a=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=wi(e);e.clearElementaryStreamInfo();var i=this.activePartLists[e.type];if(i){var r=e.sn;this.activePartLists[e.type]=Pi(i,function(e){return e.fragment.sn!==r})}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 Ri(e){var t,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(r=e.range.audiovideo)&&r.partial)}function wi(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function Pi(e,t){return e.filter(function(e){var i=t(e);return i||e.clearElementaryStreamInfo(),i})}var Di=0,Ci=1,_i=function(){return o(function e(t,i,r){a(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=i,this.aesMode=r},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case Di:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ci: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 xi=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),i=new Uint32Array(4),r=0;r<4;r++)i[r]=t.getUint32(4*r);return i}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],s=i[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 m=v^v<<1^v<<2^v<<3^v<<4;m=m>>>8^255&m^99,e[f]=m,t[m]=f;var p=h[f],y=h[p],E=h[y],T=257*h[m]^16843008*m;r[f]=T<<24|T>>>8,n[f]=T<<16|T>>>16,a[f]=T<<8|T>>>24,s[f]=T,T=16843009*E^65537*y^257*p^16843008*f,l[m]=T<<24|T>>>8,u[m]=T<<16|T>>>16,c[m]=T<<8|T>>>24,d[m]=T,f?(f=p^h[h[h[E^p]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;r<t.length&&i;)i=t[r]===this.key[r],r++;if(!i){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],m=v[1],p=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]]^m[h[l>>>16&255]]^p[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,i){for(var r,n,a,s,o,l,u,c,d,h,f,v,g,m,p=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,k=T[0],S=T[1],A=T[2],b=T[3],L=this.uint8ArrayToUint32Array_(i),I=L[0],R=L[1],w=L[2],P=L[3],D=new Int32Array(e),C=new Int32Array(D.length),_=this.networkToHostOrderSwap;t<D.length;){for(d=_(D[t]),h=_(D[t+1]),f=_(D[t+2]),v=_(D[t+3]),o=d^y[0],l=v^y[1],u=f^y[2],c=h^y[3],g=4,m=1;m<p;m++)r=k[o>>>24]^S[l>>16&255]^A[u>>8&255]^b[255&c]^y[g],n=k[l>>>24]^S[u>>16&255]^A[c>>8&255]^b[255&o]^y[g+1],a=k[u>>>24]^S[c>>16&255]^A[o>>8&255]^b[255&l]^y[g+2],s=k[c>>>24]^S[o>>16&255]^A[l>>8&255]^b[255&u]^y[g+3],o=r,l=n,u=a,c=s,g+=4;r=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],C[t]=_(r^I),C[t+1]=_(s^R),C[t+2]=_(a^w),C[t+3]=_(n^P),I=d,R=h,w=f,P=v,t+=4}return C.buffer}}])}(),Mi=function(){return o(function e(t,i,r){a(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=i,this.aesMode=r},[{key:"expandKey",value:function(){var e=function(e){switch(e){case Di:return"AES-CBC";case Ci: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 Oi=function(){return o(function e(t){var i=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).removePKCS7Padding,r=void 0===i||i;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=r,r)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 i,r,n,a=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(r=(i=a).byteLength,(n=r&&new DataView(i.buffer).getUint8(r-1))?i.slice(0,r-n):i):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,i,r){var n=this;return this.useSoftware?new Promise(function(a,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);n.softwareDecrypt(o,t,i,r);var l=n.flush();l?a(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}},{key:"softwareDecrypt",value:function(e,t,i,r){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(r!==Di||16!==t.byteLength)return Te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=rt(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(i=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new xi),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,i,r){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Mi(this.subtle,t,r)}return this.fastAesKey.expandKey().then(function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new _i(n.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return Te.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),n.onWebCryptoError(e,t,i,r)})}},{key:"onWebCryptoError",value:function(e,t,i,r){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);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,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(Te.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),Fi=Math.pow(2,17),Ni=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 i=this,r=e.url;if(!r)return Promise.reject(new Gi({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(r?"part list":"url")),networkDetails:null}));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){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void l(Ui(e));e.gap=!1}var u=i.loader=a?new a(n):new s(n),c=Bi(e);e.loader=u;var d=ui(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Fi};e.stats=u.stats;var f={onSuccess:function(t,r,n,a){i.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){i.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:fe({url:r,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:a,stats:s}))},onAbort:function(t,r,n){i.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,r,n){i.resetLoader(e,u),l(new Gi({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(i,r,n,a){return t({frag:e,part:null,payload:n,networkDetails:a})}),u.load(c,h,f)})}},{key:"loadPart",value:function(e,t,i){var r=this;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||t.gap)l(Ui(e,t));else{var u=r.loader=a?new a(n):new s(n),c=Bi(e,t);e.loader=u;var d=ui(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Fi};t.stats=u.stats,u.load(c,h,{onSuccess:function(n,a,s,l){r.resetLoader(e,u),r.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:n.data,networkDetails:l};i(c),o(c)},onError:function(i,n,a,s){r.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:fe({url:c.url,data:void 0},i),error:new Error("HTTP Error ".concat(i.code," ").concat(i.text)),networkDetails:a,stats:s}))},onAbort:function(i,n,a){e.stats.aborted=t.stats.aborted,r.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:function(i,n,a){r.resetLoader(e,u),l(new Gi({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:i}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(i.loaded/n),a),o=(a-s)*Math.round(i.loaded/s);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,u=r.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 Bi(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=i||e,n={frag:e,part:i,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,s=r.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 Ui(e,t){var i=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),r={type:J.MEDIA_ERROR,details:Z.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Gi(r)}var Gi=function(e){function t(e){var i;return a(this,t),(i=n(this,t,[e.error.message])).data=void 0,i.data=e,i}return d(t,e),o(t)}(L(Error)),Vi=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[e,i]))._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}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),Hi=o(function e(t,i,r){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=i,this.id=r,this.size=n,this.part=s,this.partial=o});var Ki={length:0,start:function(){return 0},end:function(){return 0}},ji=function(){function e(){a(this,e)}return o(e,null,[{key:"isBuffered",value:function(t,i){if(t)for(var r=e.getBuffered(t),n=r.length;n--;)if(i>=r.start(n)&&i<=r.end(n))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var i=e.getBuffered(t);return e.timeRangesToArray(i)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}},{key:"bufferInfo",value:function(t,i,r){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,i){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var r=-1,n=[];if(i)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(r=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<i?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===r&&t>=f&&t<=v&&(r=h),t+i>=f&&t<v)c=f,u=(d=v)-t;else if(t+i<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:r}}},{key:"getBuffered",value:function(e){try{return e.buffered||Ki}catch(e){return Te.log("failed to get media.buffered",e),Ki}}}])}(),Wi=/\{\$([a-zA-Z0-9-_]+)\}/g;function qi(e){return Wi.test(e)}function Yi(e,t){if(null!==e.variableList||e.hasVariableRefs){var i=e.variableList;return t.replace(Wi,function(t){var r=t.substring(2,t.length-1),n=null==i?void 0:i[r];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(r,'"'))),t):n})}return t}function zi(e,t,i){var r,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{var s=new self.URL(i).searchParams;if(!s.has(r))throw new Error('"'.concat(r,'" does not match any query parameter in URI: "').concat(i,'"'));n=s.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(t.message)))}}else r=t.NAME,n=t.VALUE;r in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(r,'"'))):a[r]=n||""}function Xi(e,t,i){var r=t.IMPORT;if(i&&r in i){var n=e.variableList;n||(e.variableList=n={}),n[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(r,'"')))}var Qi=/^(\d+)x(\d+)$/,$i=/(.+?)=(".*?"|.*?)(?:,|$)/g,Ji=function(){return o(function e(t,i){a(this,e),"string"==typeof t&&(t=e.parseAttrList(t,i)),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 i=new Uint8Array(t.length/2),r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(2*r,2*r+2),16);return i}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 i=this[e];return i?parseFloat(i):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var i=this[e];return(i?i.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=Qi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var i,r={};for($i.lastIndex=0;null!==(i=$i.exec(e));){var n=i[1].trim(),a=i[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=Yi(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":Te.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}r[n]=a}return r}}])}();function Zi(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function er(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var tr=function(){return o(function e(t,i){var r,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==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(r=null==i?void 0:i.tagOrder)?r:n,i){var s=i.attr;for(var o in s)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==s[o]){Te.warn('DATERANGE tag attribute: "'.concat(o,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=o;break}t=de(new Ji({}),s,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var l=(null==i?void 0:i.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?(Te.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)}}])}(),ir=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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>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 i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}},{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 i=e.length;i--;)if(e[i].index>t)return e[i].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 rr(e,t){return e.length===t.length&&!e.some(function(e,i){return e!==t[i]})}function nr(e,t){return!e&&!t||!(!e||!t)&&rr(e,t)}function ar(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function sr(e){switch(e){case"AES-128":case"AES-256":return Di;case"AES-256-CTR":return Ci;default:throw new Error("invalid full segment method ".concat(e))}}function or(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function lr(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function ur(e){var t=function(e,t,i){var r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function cr(e){var t,i,r=e.split(":"),n=null;if("data"===r[0]&&2===r.length){var a=r[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=or(l)):(t=lr(l).subarray(0,16),(i=new Uint8Array(16)).set(t,16-t.length),n=i)}}return n}var dr="undefined"!=typeof self?self:void 0,hr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fr="org.w3.clearkey",vr="com.apple.streamingkeydelivery",gr="com.microsoft.playready",mr="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function pr(e){switch(e){case vr:return hr.FAIRPLAY;case gr:return hr.PLAYREADY;case mr:return hr.WIDEVINE;case fr:return hr.CLEARKEY}}function yr(e){switch(e){case hr.FAIRPLAY:return vr;case hr.PLAYREADY:return gr;case hr.WIDEVINE:return mr;case hr.CLEARKEY:return fr}}function Er(e){var t=e.drmSystems,i=e.widevineLicenseUrl,r=t?[hr.FAIRPLAY,hr.WIDEVINE,hr.PLAYREADY,hr.CLEARKEY].filter(function(e){return!!t[e]}):[];return!r[hr.WIDEVINE]&&i&&r.push(hr.WIDEVINE),r}var Tr,kr=null!=dr&&null!=(Tr=dr.navigator)&&Tr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Sr(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){var a=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(a){var s=or(a).subarray(0,16);return ur(s),s}}return null}var Ar={},br=function(){function e(t,i,r){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=i,this.keyFormat=r,this.keyFormatVersions=n,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ar(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&&rr(e.keyFormatVersions,this.keyFormatVersions)&&nr(e.iv,this.iv)&&nr(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(ar(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case vr:case mr:case gr:case fr:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,i){if(!this.encrypted||!this.uri)return null;if(ar(this.method)){var r=this.iv;return r||("number"!=typeof t&&(Te.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),r=function(e){for(var t=new Uint8Array(16),i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){var n=Ar[this.uri];if(n&&!rr(this.keyId,n)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var a,s=cr(this.uri);if(s)switch(this.keyFormat){case mr:if(this.pssh=s,!this.keyId){var o=function(e){var t=[];if(e instanceof ArrayBuffer)for(var i=e.byteLength,r=0;r+32<i;){var n=ct(new DataView(e,r));t.push(n),r+=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=Lr(i));break;case gr: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=Sr(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[mr];if(t)return t.keyId;return null}(i),a||(a=Lr(i))||(a=Ar[this.uri]),a&&(this.keyId=a,e.setKeyIdForUri(this.uri,a)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){Ar={}}},{key:"setKeyIdForUri",value:function(e,t){Ar[e]=t}},{key:"addKeyIdForUri",value:function(e){var t=Object.keys(Ar).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Ar[e]=i,i}}])}();function Lr(e){var t=null==e?void 0:e[gr];if(t){var i=cr(t.uri);if(i)return Sr(i)}return null}var Ir=/#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,Rr=/#EXT-X-MEDIA:(.*)/g,wr=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Dr=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("|")),Cr=function(){function e(){a(this,e)}return o(e,null,[{key:"findGroup",value:function(e,t){for(var i=0;i<e.length;i++){var r=e[i];if(r.id===t)return r}}},{key:"resolve",value:function(e,t){return Pe.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return wr.test(e)}},{key:"parseMasterPlaylist",value:function(t,i){var r,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:qi(t)},a=[];if(Ir.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(r=Ir.exec(t));)if(r[1]){var s,o=new Ji(r[1],n),l=Yi(n,r[2]),u={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,i)},c=o.decimalResolution("RESOLUTION");c&&(u.width=c.width,u.height=c.height),Fr(o.CODECS,u);var d=o["SUPPLEMENTAL-CODECS"];d&&(u.supplemental={},Fr(d,u.supplemental)),null!=(s=u.unknownCodecs)&&s.length||a.push(u),n.levels.push(u)}else if(r[3]){var h=r[3],f=r[4];switch(h){case"SESSION-DATA":var v=new Ji(f,n),g=v["DATA-ID"];g&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[g]=v);break;case"SESSION-KEY":var m=Mr(f,i,n);m.encrypted&&m.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(m)):Te.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(f,'"'));break;case"DEFINE":zi(n,new Ji(f,n),i);break;case"CONTENT-STEERING":var p=new Ji(f,n);n.contentSteering={uri:e.resolve(p["SERVER-URI"],i),pathwayId:p["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Or(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,i,r){var n,a={},s=r.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(Rr.lastIndex=0;null!==(n=Rr.exec(t));){var u=new Ji(n[1],r),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,m=u.CHARACTERISTICS,p=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,i):""};if(v&&(y.assocLang=v),g&&(y.channels=g),m&&(y.characteristics=m),p&&(y.instreamId=p),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Nr(y,E,"audioCodec"),Nr(y,E,"textCodec")}h.push(y)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,i,r,n,a){var s,o,l,u,c,d={url:t},h=new ir(t),f=h.fragments,v=[],g=null,m=0,p=0,y=0,E=0,T=0,k=null,S=new Fe(r,d),A=-1,b=!1,L=null;if(Pr.lastIndex=0,h.m3u8=e,h.hasVariableRefs=qi(e),"#EXTM3U"!==(null==(s=Pr.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=Pr.exec(e));){b&&(b=!1,(S=new Fe(r,d)).playlistOffset=y,S.setStart(y),S.sn=m,S.cc=E,T&&(S.bitrate=T),S.level=i,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&&Gr(S,u,h),S.sn=m,S.level=i,S.cc=E,f.push(S);var w=(" "+o[3]).slice(1);S.relurl=Yi(h,w),Br(S,k,v),k=S,y+=S.duration,m++,p=0,b=!0}}else{if(!(o=o[0].match(Dr))){Te.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),D=(" "+o[l+1]).slice(1),C=o[l+2]?(" "+o[l+2]).slice(1):null;switch(P){case"BYTERANGE":k?S.setByteRange(D,k):S.setByteRange(D);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=D,S.tagList.push(["PROGRAM-DATE-TIME",D]),-1===A&&(A=f.length);break;case"PLAYLIST-TYPE":h.type&&Vr(h,P,o),h.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Vr(h,P,o):f.length>0&&Hr(h,P,o),m=h.startSN=parseInt(D);break;case"SKIP":h.skippedSegments&&Vr(h,P,o);var _=new Ji(D,h),x=_.decimalInteger("SKIPPED-SEGMENTS");if(X(x)){h.skippedSegments+=x;for(var M=x;M--;)f.push(null);m+=x}var O=_.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(O.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&Vr(h,P,o),h.targetduration=Math.max(parseInt(D),1);break;case"VERSION":null!==h.version&&Vr(h,P,o),h.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Vr(h,P,o),h.live=!1;break;case"#":(D||C)&&S.tagList.push(C?[D,C]:[D]);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,D]),T=1e3*parseInt(D),X(T)?S.bitrate=T:T=0;break;case"DATERANGE":var F=new Ji(D,h),N=new tr(F,h.dateRanges[F.ID],h.dateRangeTagCount);h.dateRangeTagCount++,N.isValid||h.skippedSegments?h.dateRanges[N.id]=N:Te.warn('Ignoring invalid DATERANGE tag: "'.concat(D,'"')),S.tagList.push(["EXT-X-DATERANGE",D]);break;case"DEFINE":var B=new Ji(D,h);"IMPORT"in B?Xi(h,B,a):zi(h,B,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?Vr(h,P,o):f.length>0&&Hr(h,P,o),h.startCC=E=parseInt(D);break;case"KEY":var U=Mr(D,t,h);if(U.isSupported()){if("NONE"===U.method){u=void 0;break}u||(u={});var G=u[U.keyFormat];null!=G&&G.matches(U)||(G&&(u=de({},u)),u[U.keyFormat]=U)}else Te.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(D,'"'));break;case"START":h.startTimeOffset=Or(D);break;case"MAP":var V=new Ji(D,h);if(S.duration){var H=new Fe(r,d);Ur(H,V,i,u),g=H,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;Ur(S,V,i,u),g=S,b=!0}g.cc=E;break;case"SERVER-CONTROL":c&&Vr(h,P,o),c=new Ji(D),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&&Vr(h,P,o);var W=new Ji(D);h.partTarget=W.decimalFloatingPoint("PART-TARGET");break;case"PART":var q=h.partList;q||(q=h.partList=[]);var Y=p>0?q[q.length-1]:void 0,z=p++,Q=new Ji(D,h),$=new Ne(Q,S,d,z,Y);q.push($),S.duration+=$.duration;break;case"PRELOAD-HINT":var J=new Ji(D,h);h.preloadHint=J;break;case"RENDITION-REPORT":var Z=new Ji(D,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(Z);break;default:Te.warn("line parsed but not handled: ".concat(o))}}}k&&!k.relurl?(f.pop(),y-=k.duration,h.partList&&(h.fragmentHint=k)):h.partList&&(Br(S,k,v),S.cc=E,h.fragmentHint=S,u&&Gr(S,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var ee=f.length,te=f[0],ie=f[ee-1];if((y+=h.skippedSegments*h.targetduration)>0&&ee&&ie){h.averagetargetduration=y/ee;var re=ie.sn;h.endSN="initSegment"!==re?re:0,h.live||(ie.endList=!0),A>0&&(!function(e,t){for(var i=e[t],r=t;r--;){var n=e[r];if(!n)return;n.programDateTime=i.programDateTime-1e3*n.duration,i=n}}(f,A),te&&v.unshift(te))}return h.fragmentHint&&(y+=h.fragmentHint.duration),h.totalduration=y,v.length&&h.dateRangeTagCount&&te&&_r(v,h),h.endCC=E,h}}])}();function _r(e,t){var i=e.length;if(!i){if(!t.hasProgramDateTime)return;var r=t.fragments[t.fragments.length-1];e.push(r),i++}for(var n=e[i-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=i;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=xr(t,u,e,c,a);if(-1!==h){l.tagAnchor=t.fragments[h].ref;break}}}}function xr(e,t,i,r,n){var a=i[r];if(a){var s,o=a.programDateTime;if(t>=o||0===r)if(t<=o+1e3*(((null==(s=i[r+1])?void 0:s.start)||n)-a.start)){var l=i[r].sn-e.startSN;if(l<0)return-1;var u=e.fragments;if(u.length>i.length)for(var c=(i[r+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 Mr(e,t,i){var r,n,a=new Ji(e,i),s=null!=(r=a.METHOD)?r:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&Te.error("Invalid IV: ".concat(a.IV));var d=o?Cr.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new br(s,d,c,h,l,a.KEYID)}function Or(e){var t=new Ji(e).decimalFloatingPoint("TIME-OFFSET");return X(t)?t:null}function Fr(e,t){var i=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text"].forEach(function(e){var r=i.filter(function(t){return ft(t,e)});r.length&&(t["".concat(e,"Codec")]=r.map(function(e){return e.split("/")[0]}).join(","),i=i.filter(function(e){return-1===r.indexOf(e)}))}),t.unknownCodecs=i}function Nr(e,t,i){var r=t[i];r&&(e[i]=r)}function Br(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Ur(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function Gr(e,t,i){e.levelkeys=t;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||r.push(e)}function Vr(e,t,i){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(i[0],")"))}function Hr(e,t,i){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(i[0],")"))}function Kr(e,t){var i=t.startPTS;if(X(i)){var r,n=0;t.sn>e.sn?(n=i-e.start,r=e):(n=e.start-i,r=t),r.duration!==n&&r.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 jr(e,t,i,r,n,a,s){r-i<=0&&(s.warn("Fragment should have a positive duration",t),r=i+t.duration,a=n+t.duration);var o=i,l=r,u=t.startPTS,c=t.endPTS;if(X(u)){var d=Math.abs(u-i);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(i,u),i=Math.min(i,u),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,l=Math.min(r,c),r=Math.max(r,c),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var h=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=n,t.endPTS=r,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,m=e.fragments;for(m[g]=t,f=g;f>0;f--)Kr(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Kr(m[f],m[f+1]);return e.fragmentHint&&Kr(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function Wr(e,t,i){if(e!==t){for(var r,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,i){for(var r=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(r?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(r&&!d&&c&&(d=t.fragments[u]=c),c&&d){i(c,d,u,o);var h=c.relurl,f=d.relurl;if(h&&en(h,f))return void(t.playlistParsingError=qr("media sequence mismatch ".concat(d.sn,":"),e,t,c,d));if(c.cc!==d.cc)return void(t.playlistParsingError=qr("discontinuity sequence mismatch (".concat(c.cc,"!=").concat(d.cc,")"),e,t,c,d))}}}(e,t,function(e,i,a,s){if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){for(var o=e.cc-i.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}X(e.startPTS)&&X(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(r=i),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.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){i.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,i){var r=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 r;return Object.keys(r).forEach(function(e){var t=a[e],n=new tr(r[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):i.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(Kt(r[e].attr),'"'))}),a}(e.dateRanges,t,i));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&&Br(u[h],u[h-1],d);_r(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=Qr(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}!function(e,t,i){if(e&&t)for(var r=0,n=0,a=e.length;n<=a;n++){var s=e[n],o=t[n+r];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?i(s,o):r--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),r?jr(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):Yr(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 m=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=m),t.driftEndTime=g,t.driftEnd=m}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function qr(e,t,i,r,n){return new Error("".concat(e," ").concat(n.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(i.startSN,"\n").concat(i.m3u8))}function Yr(e,t){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,a=r>=0,s=0;if(a&&r<n.length)s=n[r].start;else if(a&&t.startSN===e.endSN+1)s=e.fragmentEnd;else if(a&&i)s=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;s=e.fragmentStart}zr(t,s)}function zr(e,t){if(t){for(var i=e.fragments,r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Xr(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,i=1e3*e.targetduration;if(e.updated){var r=e.fragments;if(r.length&&4*i>t){var n=1e3*r[r.length-1].duration;n<i&&(i=n)}}else i/=2;return Math.round(i)}function Qr(e,t,i){if(!e)return null;var r=e.fragments[t-e.startSN];return r||((r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function $r(e,t,i){return e?Jr(e.partList,t,i):null}function Jr(e,t,i){if(e)for(var r=e.length;r--;){var n=e[r];if(n.index===i&&n.fragment.sn===t)return n}return null}function Zr(e){e.forEach(function(e,t){var i;null==(i=e.details)||i.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 i=0,r=e.length;i<r;i++){var n;if((null==(n=e[i])?void 0:n.cc)===t)return e[i]}return null}function nn(e,t){var i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function an(e,t){for(var i=t.fragments,r=0,n=i.length;r<n;r++)nn(i[r],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 i=Math.min(t.endCC,e.endCC),r=rn(t.fragments,i),n=rn(e.fragments,i);if(r&&n)Te.log("Aligning playlist at start of dicontinuity sequence ".concat(i)),an(r.start-n.start,e)}}function on(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i=e.fragments,r=t.fragments;if(i.length&&r.length){var n,a,s=Math.min(t.endCC,e.endCC);t.startCC<s&&e.startCC<s&&(n=rn(r,s),a=rn(i,s)),n&&a||(a=rn(i,(n=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.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,i){un(e,t,i),e.addEventListener(t,i)}function un(e,t,i){e.removeEventListener(t,i)}var cn=function(e){for(var t="",i=e.length,r=0;r<i;r++)t+="[".concat(e.start(r).toFixed(3),"-").concat(e.end(r).toFixed(3),"]");return t},dn="STOPPED",hn="IDLE",fn="KEY_LOADING",vn="FRAG_LOADING",gn="FRAG_LOADING_WAITING_RETRY",mn="WAITING_TRACK",pn="PARSING",yn="PARSED",En="ENDED",Tn="ERROR",kn="WAITING_INIT_PTS",Sn="WAITING_LEVEL",An=function(e){function t(e,i,r,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,i=e.fragCurrent,r=e.media,n=e.mediaBuffer,a=e.state,s=r?r.currentTime:0,o=ji.bufferInfo(n||r,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(i){var c=t.maxFragLookUpTolerance,d=i.start-c,h=i.start+i.duration+c;if(u||h<o.start||d>o.end){var f=s>h;(s<d||f)&&(f&&i.loader&&(l.log("Cancelling fragment load for seek (sn: ".concat(i.sn,")")),i.abortRequests(),l.resetLoadingState()),l.fragPrevious=null)}}if(r&&(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 Ni(e.config),l.keyLoader=r,l.fragmentTracker=i,l.config=e.config,l.decrypter=new Oi(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 i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=ji.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>r&&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 ji.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 i=this.media=this.mediaBuffer=t.media;ln(i,"seeking",this.onMediaSeeking),ln(i,"ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===dn&&this.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(e,t){var i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),un(r,"seeking",this.onMediaSeeking),un(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)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,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}},{key:"_loadFragForPlayback",value:function(e,t,i){var r=this;this._doFragLoad(e,t,i,function(e){var t=e.frag;if(r.fragContextChanged(t))return r.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(r.fragInfo(t,!1,e.part),") was dropped during download.")),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=r.state,i=e.frag;r.fragContextChanged(i)?(t===vn||!r.fragCurrent&&t===pn)&&(r.fragmentTracker.removeFragment(i),r.state=hn):("payload"in e&&(r.log("Loaded ".concat(i.type," sn: ").concat(i.sn," of ").concat(r.playlistLabel()," ").concat(i.level)),r.hls.trigger(ee.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}}).catch(function(t){r.state!==dn&&r.state!==Tn&&(r.warn("Frag error: ".concat((null==t?void 0:t.message)||t)),r.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,i=this.fragmentTracker;if(i.getState(e)===Ai){var r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),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))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===bi&&i.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 i={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(ee.BUFFER_FLUSHING,i)}}},{key:"_loadInitSegment",value:function(e,t){var i=this;this._doFragLoad(e,t).then(function(e){var t=null==e?void 0:e.frag;if(!t||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e}).then(function(e){var t=i.hls,r=e.frag,n=e.payload,a=r.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&ar(a.method)){var s=self.performance.now();return i.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,sr(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:r}),e}).then(function(n){var a=self.performance.now();return t.trigger(ee.FRAG_DECRYPTED,{frag:r,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,i.completeInitSegmentLoad(e)})}return i.completeInitSegmentLoad(e)}).catch(function(t){i.state!==dn&&i.state!==Tn&&(i.warn(t),i.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 i,r,n=e.tracks;if(n&&!t.encrypted&&(null!=(i=n.audio)&&i.encrypted||null!=(r=n.video)&&r.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 i=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(i?cn(ji.getBuffered(i)):"(detached)",")")),Oe(e)){var r;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==(r=this.levels)?void 0:r[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 i=e.frag,r=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some(function(e){return!e}),s=new Hi(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(s)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"_doFragLoad",value:function(e,t){var i,r=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!=(i=e.decryptdata)&&i.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(!r.fragContextChanged(e.frag))return r.hls.trigger(ee.KEY_LOADED,e),r.state===fn&&(r.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(i){return!i||r.fragContextChanged(i.frag)?null:r.doFragPartsLoad(e,v,t,a)}).catch(function(e){return r.handleFragLoadError(e)}):this.doFragPartsLoad(e,v,t,a).catch(function(e){return r.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,m=this.config.progressive&&e.type!==oe;return g=m&&o?o.then(function(t){return!t||r.fragContextChanged(t.frag)?null:r.fragmentLoader.load(e,a)}).catch(function(e){return r.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,m?a:void 0),o]).then(function(e){var t=p(e,1)[0];return!m&&a&&a(t),t}).catch(function(e){return r.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,i,r){var n=this;return new Promise(function(a,s){var o,l=[],u=null==(o=i.details)?void 0:o.partList,c=function(t){n.fragmentLoader.loadPart(e,t,r).then(function(r){l[t.index]=r;var s=r.part;n.hls.trigger(ee.FRAG_LOADED,r);var o=$r(i.details,e.sn,t.index+1)||Jr(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===pn){var i=t.frag,r=t.part,n=t.level,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&i.sn>s.endSN||this.shouldLoadParts(s,i.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(i.end.toFixed(2))),this.loadingParts=o),this.updateLevelTiming(i,r,n,e.partial)}else this.fragCurrent||this.state===dn||this.state===Tn||(this.state=hn)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i,r,n=e.partList[0];if(n.fragment.type===oe)return!1;if(t>=n.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0))if((this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,i=this.fragCurrent,r=e.level,n=e.sn,a=e.part;if(null==t||!t[r])return this.warn("Levels object was unset while buffering fragment ".concat(n," of ").concat(this.playlistLabel()," ").concat(r,". The current chunk will not be buffered.")),null;var s=t[r],o=s.details,l=a>-1?$r(o,n,a):null,u=l?l.fragment:Qr(o,n,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,i,r,n){if(this.state===pn){var a=e.data1,s=e.data2,o=a;if(s&&(o=rt(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:i,chunkMeta:r,offset:u,parent:t.type,data:o};if(this.hls.trigger(ee.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(ji.isBuffered(t,t.currentTime)){var i=t.currentTime,r=ji.bufferInfo(t,i,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var i,r=this.getLoadPosition();if(!X(r))return null;var n=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,n)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,i,r){var n=ji.bufferInfo(e,t,r);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,r);return ji.bufferInfo(e,t,s)}}return n}},{key:"getMaxBufferLength",value:function(e){var t,i=this.config;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)}},{key:"reduceMaxBufferLength",value:function(e,t){var i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return n>=r&&(i.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,i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}},{key:"getNextFragment",value:function(e,t){var i=t.fragments,r=i.length;if(!r)return null;var n=this.config,a=i[0].start,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: ".concat(r,", 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=i[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(i[g+1]||null,t)}return this.mapToInitFragWhenRequired(v)}},{key:"isLoopLoading",value:function(e,t){var i=this.fragmentTracker.getState(e);return(i===Li||i===bi&&!!e.gap)&&this.nextLoadPosition>t}},{key:"getNextFragmentLoopLoading",value:function(e,t,i,r,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&i.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==s&&i.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(r,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(bn(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(bn(this.config)&&e.type!==oe){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var n=r.event;if(n){if(n.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}var a=null==i?void 0:i.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,i){for(var r=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,r>-1&&i<l.start)break;var u=l.loaded;u?r=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn("Need buffer at ".concat(i," but next unloaded part starts at ").concat(l.start)),r=s),n=u}return r}},{key:"loadedEndOfParts",value:function(e,t){for(var i,r=e.length;r--;){if(!(i=e[r]).loaded)return!1;if(t>i.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(i.programDateTime)),r=function(e,t,i){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 r=0;r<e.length;++r){var n=e[r];if(ii(t,i,n))return n}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(r.sn)))}r||(r=ri(e,i.cc,i.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(r.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(r=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}},{key:"getFragmentAtPosition",value:function(e,t,i){var r,n,a=this.config,s=this.fragPrevious,o=i.fragments,l=i.endSN,u=i.fragmentHint,c=a.maxFragLookUpTolerance,d=i.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)?r=ei(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:c):r=o[o.length-1];if(r){var f=r.sn-i.startSN,v=this.fragmentTracker.getState(r);if((v===Li||v===bi&&r.gap)&&(s=r),s&&r.sn===s.sn&&(!h||d[0].fragment.sn>r.sn||!i.live))if(r.level===s.level){var g=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(g)!==Li?g:null}}return r}},{key:"alignPlaylists",value:function(e,t,i){var r=e.fragments.length;if(!r)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||Yr(e,t,!1))}(i,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(r)),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 i=this.startPosition;i<t&&(i=-1);var r=this.timelineOffset;if(-1===i){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;null!==a&&X(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log("Setting startPosition to ".concat(i," for start time offset ").concat(a," found in ").concat(n?"multivariant":"media"," playlist")),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge ".concat(i)),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}},{key:"getLoadPosition",value:function(){var e,t=this.media,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}},{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 i;if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.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===gi,g=f&&!o.resolved&&u===pi,m=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!v&&g&&Oe(n)&&!n.endList&&m&&!si(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var p,y=di(null==(p=t.response)?void 0:p.code),E=li(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===vi||(o.resolved=!0)}else this.state=l===fi?Sn:Tn;this.tickImmediate()}else this.state=Tn}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!di(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=hn)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===pn||this.state===yn){var t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.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(i," 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,i){if(e){var r=ji.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),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,i,r){var n=this,a=i.details;if(a){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=r?0:jr(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n);return n.hls.trigger(ee.LEVEL_PTS_UPDATED,{details:a,level:i,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1)){var s,o=null===(null==(s=this.transmuxer)?void 0:s.error);if((0===i.fragmentError||o&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),o){var l=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(l.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(i.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,i,r=!(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=r&&!n?e.startPTS:(n||e).start)?t:NaN).toFixed(3),"-").concat((null!=(i=r&&!n?e.endPTS:(n||e).end)?i: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)))}}])}(Vi);function bn(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,i=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var i=new Uint8Array(t),r=0,n=0;n<e.length;n++){var a=e[n];i.set(a,r),r+=a.length}return i}(t,i),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,i="~";function r(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,r,a,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new n(r,a||e,s),l=i?i+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 r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,n=[];if(0===this._eventsCount)return n;for(r in e=this._events)t.call(e,r)&&n.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,a=r.length,s=new Array(a);n<a;n++)s[n]=r[n].fn;return s},o.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,n,a,s){var o=i?i+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,r),!0;case 4:return c.fn.call(c.context,t,r,n),!0;case 5:return c.fn.call(c.context,t,r,n,a),!0;case 6:return c.fn.call(c.context,t,r,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,r);break;case 4:c[u].fn.call(c[u].context,t,r,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,i){return a(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,r,n){var a=i?i+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||r&&o.context!==r||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||n&&!o[l].once||r&&o[l].context!==r)&&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=i?i+e:e,this._events[t]&&s(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(Rn)),Rn.exports),Pn=Ie(wn),Dn="1.6.15",Cn={};function _n(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 xn(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 i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3]}function On(e,t){for(var i=t,r=0;xn(e,t);){r+=10,r+=Mn(e,t+6),_n(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)}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 Bn(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Un(e,t){return t+1<e.length&&Fn(e,t)}function Gn(e,t){if(Un(e,t)){var i=Nn(e,t);if(t+i>=e.length)return!1;var r=Bn(e,t);if(r<=i)return!1;var n=t+r;return n===e.length||Un(e,n)}return!1}function Vn(e,t,i,r,n){if(!e.samplerate){var a=function(e,t,i,r){var n=t[i+2],a=n>>2&15;if(!(a>12)){var s=1+(n>>6&3),o=t[i+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 Te.log("manifest codec:".concat(r,", 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:r}}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,i,r,n);if(!a)return;de(e,a)}}function Hn(e){return 9216e4/e}function Kn(e,t,i,r,n){var a,s=r+n*Hn(e.samplerate),o=function(e,t){var i=Nn(e,t);if(t+i<=e.length){var r=Bn(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,i+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(i+u,t.length),0):a=t.subarray(i+u,i+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-i;return(a=new Uint8Array(f)).set(t.subarray(i,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}function jn(e,t){return xn(e,t)&&Mn(e,t+6)+10<=e.length-t}function Wn(e){return function(e,t,i,r){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),a=1;"BYTES_PER_ELEMENT"in r&&(a=r.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(i,0),o));var d;return new r(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 qn(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var i=e.data.subarray(1).indexOf(0);if(-1!==i){var r=Ae(Wn(e.data,1,i)),n=e.data[2+i],a=e.data.subarray(3+i).indexOf(0);if(-1!==a){var s,o=Ae(Wn(e.data,3+i,a));return s="--\x3e"===r?Ae(Wn(e.data,4+i+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+i+a)),t.mimeType=r,t.pictureType=n,t.description=o,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function Yn(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Ae(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,i=Ae(e.data.subarray(t),!0);t+=i.length+1;var r=Ae(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Ae(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?qn(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,i=Ae(e.data.subarray(t),!0);t+=i.length+1;var r=Ae(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Ae(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]),i=Mn(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}function Xn(e){for(var t=0,i=[];xn(e,t);){var r=Mn(e,t+6);e[t+5]>>6&1&&(t+=10);for(var n=(t+=10)+r;t+10<n;){var a=zn(e.subarray(t)),s=Yn(a);s&&i.push(s),t+=a.size+10}_n(e,t)&&(t+=10)}return i}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),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Jn(e){for(var t=Xn(e),i=0;i<t.length;i++){var r=t[i];if(Qn(r))return $n(r)}}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,i,r){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,i){}},{key:"demux",value:function(e,t){this.cachedData&&(e=rt(this.cachedData,e),this.cachedData=null);var i,r=On(e,0),n=r?r.length:0,a=this._audioTrack,s=this._id3Track,o=r?Jn(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&X(o))&&(this.basePTS=ia(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,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,i=n+=u.length):n=l}else jn(e,n)?(r=On(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY}),i=n+=r.length):n++;if(n===l&&i!==l){var c=e.slice(i);this.cachedData?this.cachedData=rt(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:ea(),id3Track:s,textTrack:ea()}}},{key:"demuxSampleAes",value:function(e,t,i){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}}])}(),ia=function(e,t,i){return X(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0)},ra=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,i,r,n){if(!(i+24>t.length)){var a=ua(t,i);if(a&&i+a.frameLength<=t.length){var s=r+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(i,i+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 i=e[t+1]>>3&3,r=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*na[14*(3===i?3-r:3===r?3:4)+n-1],u=aa[3*(3===i?0:2===i?1:2)+a],c=3===o?1:2,d=sa[i][r],h=oa[r],f=8*d*h,v=Math.floor(d*l/u+s)*h;if(null===ra){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ra=g?parseInt(g[1]):0}return!!ra&&ra<=87&&2===r&&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 i=ua(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);var n=t+r;return n===e.length||da(e,n)}return!1}var fa=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t)).observer=void 0,r.config=void 0,r.observer=e,r.config=i,r}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,i,r,n){E(t,"resetInitSegment",this,3)([e,i,r,n]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,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)&&Bn(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,i){Vn(e,this.observer,t,i,e.manifestCodec);var r=Kn(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}}],[{key:"probe",value:function(e,t){if(!e)return!1;var i=On(e,0),r=(null==i?void 0:i.length)||0;if(ha(e,r))return!1;for(var n=e.length;r<n;r++)if(Gn(e,r))return t.log("ADTS sync word found !"),!0;return!1}}])}(ta),va=function(e,t){var i=0,r=5;t+=r;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);r>0;){s[0]=e[t];var o=Math.min(r,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,i=i?i<<o|n[0]:n[0],t+=1,r-=o}return i},ga=function(e){function t(e){var i;return a(this,t),(i=n(this,t)).observer=void 0,i.observer=e,i}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,i,r,n){E(t,"resetInitSegment",this,3)([e,i,r,n]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,i){var r=ma(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0);if(!t)return!1;var i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Jn(t)&&va(e,i)<16}}])}(ta);function ma(e,t,i,r,n){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;var a=t[i+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[i+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(i+l>t.length)return-1;var u=t[i+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[i+6]<<8|t[i+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[i+5]>>3,v=7&t[i+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),m=r+n*(1536/s*9e4),p=t.subarray(i,i+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:p,pts:m}),l}var pa=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,i,r,n){E(t,"resetInitSegment",this,3)([e,i,r,n]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,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,i){if(null!==this.basePTS)return la(e,t,i,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Jn(t)&&va(e,i)<=16)return!1;for(var r=e.length;i<r;i++)if(ha(e,i))return Te.log("MPEG Audio sync word found !"),!0;return!1}}])}(ta),ya=/\/emsg[-/]ID3/i,Ea=function(){return o(function e(t,i){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=i},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,i,r){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,m=f.codec;a.id=v,a.timescale=g,a.codec=m}s.id=Ve.text,n.sampleDuration=0,n.duration=a.duration=r}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t){this.timeOffset=t;var i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=rt(this.remainderData,e));var a=function(e){var t={valid:null,remainder:null},i=Ye(e,["moof"]);if(i.length<2)return t.remainder=e,t;var r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=a.remainder,r.samples=a.valid||new Uint8Array}else r.samples=i;var s=this.extractID3Track(r,t);return n.samples=nt(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}},{key:"flush",value:function(){var e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(t,this.timeOffset);return i.samples=nt(e,t),{videoTrack:t,audioTrack:ea(),id3Track:r,textTrack:ea()}}},{key:"extractID3Track",value:function(e,t){var i=this,r=this.id3Track;if(e.samples.length){var n=Ye(e.samples,["emsg"]);n&&n.forEach(function(e){var n=function(e){var t=e[0],i="",r="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==He(e.subarray(u,u+1));)i+=He(e.subarray(u,u+1)),u+=1;for(i+=He(e.subarray(u,u+1)),u+=1;"\0"!==He(e.subarray(u,u+1));)r+=He(e.subarray(u,u+1)),u+=1;r+=He(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,Te.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"!==He(e.subarray(u,u+1));)i+=He(e.subarray(u,u+1)),u+=1;for(i+=He(e.subarray(u,u+1)),u+=1;"\0"!==He(e.subarray(u,u+1));)r+=He(e.subarray(u,u+1)),u+=1;r+=He(e.subarray(u,u+1)),u+=1}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(ya.test(n.schemeIdUri)){var a=Ta(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;r.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Zn.emsg,duration:s})}else if(i.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=Ta(n,t);r.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Zn.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}},{key:"demuxSampleAes",value:function(e,t,i){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,i=0;i<t;){var r=je(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)}}])}();function Ta(e,t){return X(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var ka=function(){return o(function e(t,i,r){a(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Oi(i,{removePKCS7Padding:!1})},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Di)}},{key:"decryptAacSample",value:function(e,t,i){var r=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),r.decrypter.isSync()||r.decryptAacSamples(e,t+1,i)}).catch(i)}}},{key:"decryptAacSamples",value:function(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var i=new Uint8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}},{key:"decryptAvcSample",value:function(e,t,i,r,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,i+1,r)}).catch(r)}},{key:"decryptAvcSamples",value:function(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();for(var n=e[t].units;!(i>=n.length);i++){var a=n[i];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,i,r,a),this.decrypter.isSync())))return}}}}])}(),Sa=function(){return o(function e(){a(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){var n=r.units;i=n[n.length-1]}return i}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var i=t.samples,r=i.length;if(!r)return void t.dropped++;var n=i[r-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,i){var r,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(r=t[u++],s)if(1!==s)if(r)if(1===r){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=rt(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=r?0:2;else s=r?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=rt(g.data,t))}return e.naluState=s,l}}])}(),Aa=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,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.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),i=this.word>>>32-t;if(e>32&&Te.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?i<<t|this.readBits(t):i}},{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)}}])}(),ba=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,i,r){var n,a=this,s=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(function(r){var s,u;switch(r.type){case 1:var c=!1;n=!0;var d,h=r.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,i.pts,i.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,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,ot(r.data,1,i.pts,t.samples);break;case 7:var v,g;n=!0,l=!0;var m=r.data,p=a.readSPS(m);if(!e.sps||e.width!==p.width||e.height!==p.height||(null==(v=e.pixelRatio)?void 0:v[0])!==p.pixelRatio[0]||(null==(g=e.pixelRatio)?void 0:g[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[m];for(var y=m.subarray(1,4),E="avc1.",T=0;T<3;T++){var k=y[T].toString(16);k.length<2&&(k="0"+k),E+=k}e.codec=E}break;case 8:n=!0,e.pps=[r.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,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(r)}),r&&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 Aa(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var i=8,r=8,n=0;n<e;n++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r}},{key:"readSPS",value:function(e){var t,i,r,n=new Aa(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),m=this.skipScalingList.bind(this);u();var p=u();if(c(5),f(3),u(),g(),100===p||110===p||122===p||244===p||44===p||83===p||86===p||118===p||128===p){var y=d();if(3===y&&f(1),g(),g(),f(1),h())for(i=3!==y?8:12,r=0;r<i;r++)h()&&m(r<6?16:64,n)}g();var E=d();if(0===E)d();else if(1===E)for(f(1),v(),v(),t=d(),r=0;r<t;r++)v();g(),f(1);var T=d(),k=d(),S=c(1);0===S&&f(1),f(1),h()&&(a=d(),s=d(),o=d(),l=d());var A=[1,1];if(h()&&h())switch(u()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(T+1)-2*a-2*s),height:(2-S)*(k+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}])}(Sa),La=function(e){function t(){var e;a(this,t);for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return(e=n(this,t,[].concat(r))).initVPS=null,e}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,i,r){var n,a=this,s=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(function(r){var s,u;switch(r.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,i.pts,i.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,i.pts,i.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,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:n=!0,ot(r.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!==S(e.params)&&(e.params={}),e.params=de(e.params,a.readVPS(r.data)),a.initVPS=r.data),e.vps=[r.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],r.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var d=a.readSPS(r.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,r.data,e.vps),o||(o=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(n=!0,"object"===S(e.params)){if(!e.pps){e.pps=[];var f=a.readPPS(r.data);for(var v in f)e.params[v]=f[v]}a.pushParameterSet(e.pps,r.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,i.pts,i.dts));break;default:n=!1}o&&n&&o.units.push(r)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,i){(i&&i[0]===this.initVPS||!i&&!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),i=0,r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}},{key:"pushAccessUnit",value:function(e,i){E(t,"pushAccessUnit",this,3)([e,i]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new Aa(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 Aa(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var i=t.readBits(3);t.readBoolean();for(var r=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(),m=t.readUByte(),p=[],y=[],E=0;E<i;E++)p.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(var T=i;T<8;T++)t.readBits(2);for(var k=0;k<i;k++)p[k]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[k]&&t.readUByte();t.readUEG();var S=t.readUEG();3==S&&t.skipBits(1);var A=t.readUEG(),b=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 D=t.readUEG(),C=t.readUEG(),_=t.readUEG(),x=t.readBoolean()?0:i;x<=i;x++)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 B=t.readUEG(),U=0,G=0;G<B;G++){var V=!1;if(0!==G&&(V=t.readBoolean()),V){G===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var H=0,K=0;K<=U;K++){var j=t.readBoolean(),W=!1;j||(W=t.readBoolean()),(j||W)&&H++}U=H}else{var q=t.readUEG(),Y=t.readUEG();U=q+Y;for(var z=0;z<q;z++)t.readUEG(),t.readBoolean();for(var X=0;X<Y;X++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var Q=t.readUEG(),$=0;$<Q;$++){for(var J=0;J<_+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,ie=!0,re=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(re=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<=i;ue++){var ce=!1;(ie=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=A,ge=b;if(L){var me=1,pe=1;1===S?me=pe=2:2==S&&(me=2),ve=A-me*R-me*I,ge=b-pe*P-pe*w}for(var ye=r?["A","B","C"][r]:"",Ee=s<<24|o<<16|l<<8|u,Te=0,ke=0;ke<32;ke++)Te=(Te|(Ee>>ke&1)<<31-ke)>>>0;var Se=Te.toString(16);1===a&&"2"===Se&&(Se="6");var Ae=n?"H":"L";return{codecString:"hvc1.".concat(ye).concat(a,".").concat(Se,".").concat(Ae).concat(m,".B0"),params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:m,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:C,min_spatial_segmentation_idc:Z,chroma_format_idc:S,frame_rate:{fixed:ie,fps:ne/re}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new Aa(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 i=t.readBoolean(),r=t.readBoolean(),n=1;return r&&i?n=0:r?n=3:i&&(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,i,r,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=i,this.typeSupported=r,this.logger=n,this.videoParser=null}return o(e,[{key:"resetInitSegment",value:function(t,i,r,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=i,this.videoCodec=r}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,i=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,i){var r,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,m=null,p=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=rt(this.remainderData,t)).length,this.remainderData=null),E<Ia&&!a)return this.remainderData=t,{audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};var T=Math.max(0,e.syncOffset(t));(E-=(E-T)%Ia)<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var k=0,S=T;S<E;S+=Ia)if(71===t[S]){var A=!!(64&t[S+1]),b=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(b){case c:A&&(d&&(r=xa(d,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,u,r,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(L,S+Ia)),d.size+=S+Ia-L);break;case h:if(A){if(v&&(r=xa(v,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r)}v={data:[],size:0}}v&&(v.data.push(t.subarray(L,S+Ia)),v.size+=S+Ia-L);break;case f:A&&(g&&(r=xa(g,this.logger))&&this.parseID3PES(l,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(L,S+Ia)),g.size+=S+Ia-L);break;case 0:A&&(L+=t[L]+1),y=this._pmtId=Pa(t,L);break;case y:A&&(L+=t[L]+1);var I=Da(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===m||p||(this.logger.warn("MPEG-TS PMT found at ".concat(S," after unknown PID '").concat(m,"'. Backtracking to sync byte @").concat(T," to parse all TS packets.")),m=null,S=T-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=b}}else k++;k>0&&Ca(this.observer,new Error("Found ".concat(k," 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,i=e.audioTrack,r=e.videoTrack,n=e.id3Track,a=e.textTrack,s=r.pesData,o=i.pesData,l=n.pesData;if(s&&(t=xa(s,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,a,t,!0),r.pesData=null)):r.pesData=s,o&&(t=xa(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=xa(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l}},{key:"demuxSampleAes",value:function(e,t,i){var r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new ka(this.observer,this.config,t);return this.decrypt(r,n)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new ba:"hevc"===e&&(this.videoParser=new La))}},{key:"decrypt",value:function(e,t){return new Promise(function(i){var r=e.audioTrack,n=e.videoTrack;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,function(){n.samples?t.decryptAvcSamples(n.samples,0,0,function(){i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,function(){i(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 i,r,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=rt(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(i=a,r=o.length;i<r-1&&!Un(o,i);i++);if(i!==a){var d,h=i<r-1;if(d=h?"AAC PES did not start with ADTS header,offset:".concat(i):"No ADTS header found in AAC PES",Ca(this.observer,new Error(d),h,this.logger),!h)return}if(Vn(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)n=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=Hn(e.samplerate);n=s.sample.pts+f}for(var v,g=0;i<r;){if(i+=(v=Kn(e,o,i,n,g)).length,v.missing){this.aacOverFlow=v;break}for(g++;i<r-1&&!Un(o,i);i++);}}},{key:"parseMPEGPES",value:function(e,t){var i=t.data,r=i.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<r;)if(da(i,a)){var o=la(e,i,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 i=t.data,r=t.pts;if(void 0!==r)for(var n,a=i.length,s=0,o=0;o<a&&(n=ma(e,i,o,r,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 i=de({},t,{type:this._videoTrack?Zn.emsg:Zn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}}],[{key:"probe",value:function(t,i){var r=e.syncOffset(t);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset ".concat(r)),-1!==r}},{key:"syncOffset",value:function(e){for(var t=e.length,i=Math.min(940,t-Ia)+1,r=0;r<i;){for(var n=!1,a=-1,s=0,o=r;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)&&(i=Math.min(a+18612,e.length-Ia)+1),n||(n=0===wa(e,o)),n&&s>1&&(0===a&&s>2||o+Ia>i))return a}r++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Ve[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 Da(e,t,i,r,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(!r){_a("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(!r){_a("H.264",a);break}case 27:-1===s.videoPid&&(s.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){_a("AC-3",a);break}case 129:i.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!==i.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 Ca(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 Ca(e,t,i,r){r.warn("parsing error: ".concat(t.message)),e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function _a(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function xa(e,t){var i,r,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]=rt(l[0],l[1]),l.splice(1,1);if(1===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;var u=i[7];192&u&&(a=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&u?a-(s=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[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=i[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=(i=l[h]).byteLength;if(c){if(c>v){c-=v;continue}i=i.subarray(c),v-=c,c=0}d.set(i,o),o+=v}return r&&(r-=n+3),{data:d,pts:a,dts:s,len:r}}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 i=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]),r=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:i,audio:r};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,i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];for(var a=r.length,s=a;a--;)t+=r[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(r[a],t),t+=r[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,i){i*=t;var r=Math.floor(i/(Oa+1)),n=Math.floor(i%(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,r>>24,r>>16&255,r>>8&255,255&r,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,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))}},{key:"moov",value:function(t){for(var i=t.length,r=[];i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var i=t.length,r=[];i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex].concat(r))}},{key:"mvhd",value:function(t,i){i*=t;var r=Math.floor(i/(Oa+1)),n=Math.floor(i%(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,r>>24,r>>16&255,r>>8&255,255&r,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 i,r,n=t.samples||[],a=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,a[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.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 i,r,n,a=[],s=[];for(i=0;i<t.sps.length;i++)n=(r=t.sps[i]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)n=(r=t.pps[i]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));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(T(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 i=t.segmentCodec;if("audio"===t.type){if("aac"===i)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===i&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===i&&"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"===i)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===i&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(i,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var i=t.id,r=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(r/(Oa+1)),o=Math.floor(r%(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,i>>24&255,i>>16&255,i>>8&255,255&i,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,i){var r=e.sdtp(t),n=t.id,a=Math.floor(i/(Oa+1)),s=Math.floor(i%(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,r.length+16+20+8+16+8+8),r)}},{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 i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,i){var r,n,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(i+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<c;r++)a=(n=u[r]).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*r);return e.box(e.types.trun,h)}},{key:"initSegment",value:function(t){e.types||e.init();var i=e.moov(t);return rt(e.FTYP,i)}},{key:"hvc1",value:function(t){for(var i=t.params,r=[t.vps,t.sps,t.pps],n=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),a=n.length,s=0;s<r.length;s+=1){a+=3;for(var o=0;o<r[s].length;o+=1)a+=2+r[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=r.length-1,c=0;c<r.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,r[c].length]),a),a+=3;for(var d=0;d<r[c].length;d+=1)l.set(new Uint8Array([r[c][d].length>>8,255&r[c][d].length]),a),a+=2,l.set(r[c][d],a),a+=r[c][d].length}var h=e.box(e.types.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],m=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,m>>24,m>>16&255,m>>8&255,255&m])))}}])}();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 i=e*t*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(i):i}function Ba(e){return Na(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function Ua(e){var t=e.baseTime,i=e.timescale,r=e.trackId;return"".concat(t/i," (").concat(t,"/").concat(i,") trackId: ").concat(r)}var Ga=null,Va=null;function Ha(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ka=function(e){function t(e,i,r,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=i,o.typeSupported=r,o.ISGenerated=!1,null===Ga){var l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ga=l?parseInt(l[1]):0}if(null===Va){var u=navigator.userAgent.match(/Safari\/(\d+)/i);Va=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?Ua(t):t," > ").concat(e?Ua(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,i=e[0].pts,r=e.reduce(function(e,r){var n=r.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=ja(n,i))-e),a>0?e:n},i);return t&&this.debug("PTS rollover detected"),r}},{key:"remux",value:function(e,t,i,r,n,a,s,o){var l,u,c,d,h,f,v=n,g=n,m=e.pid>-1,p=t.pid>-1,y=t.samples.length,E=e.samples.length>0,T=s&&y>0||y>1;if((!m||E)&&(!p||T)||this.ISGenerated||s){if(this.ISGenerated){var k,S,A,b,L=this.videoTrackConfig;(L&&(t.width!==L.width||t.height!==L.height||(null==(k=t.pixelRatio)?void 0:k[0])!==(null==(S=L.pixelRatio)?void 0:S[0])||(null==(A=t.pixelRatio)?void 0:A[1])!==(null==(b=L.pixelRatio)?void 0:b[1]))||!L&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));var I,R=this.isVideoContiguous,w=-1;if(T&&(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&&T){var D=this.getVideoStartPts(t.samples),C=(ja(e.samples[0].pts,D)-D)/t.inputTimeScale;v+=Math.max(0,C),g+=Math.max(0,-C)}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,p||T||o===se?g:void 0),T){var _=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,_)}}else T&&(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&&(i.samples.length&&(h=Wa(i,n,this._initPTS,this._initDTS)),r.samples.length&&(d=qa(r,n,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}},{key:"computeInitPts",value:function(e,t,i,r){var n=Math.round(i*t),a=ja(e,n);if(a<n+t)for(this.log("Adjusting PTS for rollover in timeline near ".concat((n-a)/t," ").concat(r));a<n+t;)a+=8589934592;return a-n}},{key:"generateIS",value:function(e,t,i,r){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||r,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,i,"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),m=ja(l[0].dts,g),p=this.computeInitPts(m,s,i,"video"),y=this.computeInitPts(g,s,i,"video");a=Math.min(a,p),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(r?"":"~").concat(i," ").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(i," 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,i,r){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,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||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?i=!0:h=y-E-d}for(var T=h+d,k=0;k<u;k++){var S=o[k];S.pts=ja(S.pts,T),S.dts=ja(S.dts,T),S.dts<o[k>0?k-1:k].dts&&(p=!0)}p&&o.sort(function(e,t){var i=e.dts-t.dts,r=e.pts-t.pts;return i||r}),n=o[0].dts;var A=(a=o[o.length-1].dts)-n,b=A?Math.round(A/(u-1)):v||e.inputTimeScale/30;if(i){var L=n-T,I=L>b,R=L<-1;if((I||R)&&(I?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ba(L,!0)," ms (").concat(L,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ba(-L,!0)," ms (").concat(L,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!R||T>=o[0].pts||Ga)){n=T;var w=o[0].pts-L;if(I)o[0].dts=n,o[0].pts=w;else for(var P=!0,D=0;D<o.length&&!(o[D].dts>w&&P);D++){var C=o[D].pts;if(o[D].dts-=L,o[D].pts-=L,D<o.length-1){var _=o[D+1].pts;P=_<=o[D].pts==_<=C}}this.log("Video: Initial PTS/DTS adjusted: ".concat(Ba(w,!0),"/").concat(Ba(n,!0),", delta: ").concat(Ba(L,!0)," ms"))}}for(var x=0,M=0,O=n=Math.max(0,n),F=0;F<u;F++){for(var N=o[F],B=N.units,U=B.length,G=0,V=0;V<U;V++)G+=B[V].data.length;M+=G,x+=U,N.length=G,N.dts<O?(N.dts=O,O+=b/4|0||1):O=N.dts,g=Math.min(N.pts,g),m=Math.max(N.pts,m)}a=o[u-1].dts;var H,K=M+4*x+8;try{H=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(H.buffer);j.setUint32(0,K),H.set(Fa.types.mdat,4);for(var W=!1,q=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<u;Q++){for(var $=o[Q],te=$.units,ie=0,re=0,ne=te.length;re<ne;re++){var ae=te[re],se=ae.data,oe=ae.data.byteLength;j.setUint32(f,oe),f+=4,H.set(se,f),f+=oe,ie+=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:b;if(le=Q>0?$.pts-o[Q-1].pts:b,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var he=Math.floor(ue.maxBufferHole*s),fe=(r?g+r*s:this.nextAudioTs+d)-$.pts;fe>he?((v=fe-ce)<0?v=ce:W=!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);q=Math.min(q,v),z=Math.max(z,v),Y=Math.min(Y,le),X=Math.max(X,le),l.push(Ha($.key,v,ie,ve))}if(l.length)if(Ga){if(Ga<70){var ge=l[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(Va&&X-Y<z-q&&b/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 me=n,pe=0,ye=l.length;pe<ye;pe++){var Ee=me+l[pe].duration,Te=me+l[pe].cts;if(pe<ye-1){var ke=Ee+l[pe+1].cts;l[pe].duration=ke-Te}else l[pe].duration=pe?l[pe-1].duration:b;l[pe].cts=0,me=Ee}}var Se=a+(v=W||!v?b:v);this.nextVideoTs=h=Se-d,this.videoSampleDuration=v,this.isVideoContiguous=!0;var Ae={data1:Fa.moof(e.sequenceNumber++,n,de(e,{samples:l})),data2:H,startPTS:(g-d)/s,endPTS:(m+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,Ae}},{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,i,r,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,m=u.baseTime*a/u.timescale,p=m+t*a;if(this.isAudioContiguous=i=i||f.length&&g>0&&(r&&Math.abs(p-(g+m))<9e3||Math.abs(ja(f[0].pts,p)-(g+m))<20*l),f.forEach(function(e){e.pts=ja(e.pts,p)}),!i||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(m," / ").concat(a,")")),!f.length)return;g=0===n?0:r&&!h?Math.max(0,p-m):f[0].pts-m}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,T=0,k=g+m;T<f.length;T++){var S=f[T],A=S.pts,b=A-k,L=Math.abs(1e3*b/a);if(b<=-E*l&&h)0===T&&(this.warn("Audio frame @ ".concat((A/a).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*b/a)," ms.")),this.nextAudioTs=g=A-m,k=A);else if(b>=E*l&&L<1e4&&h){var I=Math.round(b/l);for(k=A-I*l;k<0&&I&&l;)I--,k+=l;0===T&&(this.nextAudioTs=g=k-m),this.warn("Injecting ".concat(I," audio frames @ ").concat(((k-m)/a).toFixed(3),"s due to ").concat(Math.round(1e3*b/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(T,0,{unit:w,pts:k}),k+=l,T++}}S.pts=k,k+=l}for(var P,D=null,C=null,_=0,x=f.length;x--;)_+=f[x].unit.byteLength;for(var M=0,O=f.length;M<O;M++){var F=f[M],N=F.unit,B=F.pts;if(null!==C){d[M-1].duration=Math.round((B-C)/s)}else{if(i&&"aac"===e.segmentCodec&&(B=g+m),D=B,!(_>0))return;_+=v;try{P=new Uint8Array(_)}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:_,reason:"fail allocating audio mdat ".concat(_)})}c||(new DataView(P.buffer).setUint32(0,_),P.set(Fa.types.mdat,4))}P.set(N,v);var U=N.byteLength;v+=U,d.push(Ha(!0,o,U,0)),C=B}var G=d.length;if(G){var V=d[d.length-1];g=C-m,this.nextAudioTs=g+s*V.duration;var H=c?new Uint8Array(0):Fa.moof(e.sequenceNumber++,D/s,de({},e,{samples:d}));e.samples=[];var K=(D-m)/a,j=this.nextAudioTs/a,W={data1:H,data2:P,startPTS:K,endPTS:j,startDTS:K,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:G};return this.isAudioContiguous=!0,W}}}])}(ve);function ja(e,t){var i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function Wa(e,t,i,r){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-i.baseTime*a/i.timescale,t*a)/a,o.dts=ja(o.dts-r.baseTime*a/r.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function qa(e,t,i){var r=e.samples.length;if(r){for(var n=e.inputTimeScale,a=0;a<r;a++){var s=e.samples[a];s.pts=ja(s.pts-i.baseTime*n/i.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 Ya,za=function(e){function t(e,i,r,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,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t){var i=this.audioCodec,r=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 i=t.keyId;i&&t.isCommonEncryption&&tt(e,function(e,t){var r=e.subarray(8,24);r.some(function(e){return 0!==e})||(Te.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(be(r)," -> ").concat(be(i))),e.set(i,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&&(i=Qa(a,Ce,this)),s&&(r=Qa(s,_e,this));var l={};a&&s?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:i,encrypted:a.encrypted,initSegment:e,id:"audio"}:s?l.video={container:"video/mp4",codec:r,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,i,r,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,c={audio:void 0,video:void 0,text:r,id3:i,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,i){for(var r={},n=Ye(e,["moof","traf"]),a=0;a<n.length;a++){var s=n[a],o=Ye(s,["tfhd"])[0],l=je(o,4),u=t[l];if(u){r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:u.timescale,type:u.type});var c=r[l],d=Ye(s,["tfdt"])[0];if(d){var h=d[0],f=je(d,4);1===h&&(f===Ue?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=Ue+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),m=(null==v?void 0:v.duration)||0;8&g&&(m=je(o,2&g?12:8));for(var p=Ye(s,["trun"]),y=c.start||0,E=0,T=m,k=0;k<p.length;k++){var S=p[k],A=je(S,4),b=c.sampleCount;c.sampleCount+=A;var L=1&S[3],I=4&S[3],R=1&S[2],w=2&S[2],P=4&S[2],D=8&S[2],C=8,_=A;for(L&&(C+=4),I&&A&&(1&S[C+1]||void 0!==c.keyFrameIndex||(c.keyFrameIndex=b),C+=4,R?(T=je(S,C),C+=4):T=m,w&&(C+=4),D&&(C+=4),y+=T,E+=T,_--);_--;)R?(T=je(S,C),C+=4):T=m,w&&(C+=4),P&&(1&S[C+1]||void 0===c.keyFrameIndex&&(c.keyFrameIndex=c.sampleCount-(_+1),c.keyFrameStart=y),C+=4),D&&(C+=4),y+=T,E+=T;!E&&m&&(E+=m*A)}c.duration+=E}}if(!Object.keys(r).some(function(e){return r[e].duration})){for(var x=1/0,M=0,O=Ye(e,["sidx"]),F=0;F<O.length;F++){var N=ze(O[F]);if(null!=N&&N.references){x=Math.min(x,N.earliestPresentationTime/N.timescale);var B=N.references.reduce(function(e,t){return e+t.info.duration||0},0);M=Math.max(M,B+N.earliestPresentationTime/N.timescale)}}M&&X(M)&&Object.keys(r).forEach(function(e){r[e].duration||(r[e].duration=M*r[e].timescale-r[e].start)})}return r}(d,f,this),g=f.audio?v[f.audio.id]:null,m=f.video?v[f.video.id]:null,p=Xa(m,1/0),y=Xa(g,1/0),E=Xa(m,0,!0),T=Xa(g,0,!0),k=n,S=0,A=g&&(!m||!l&&y<p||l&&l.trackId===f.audio.id),b=A?g:m;if(b){var L=b.timescale,I=b.start-n*L,R=A?f.audio.id:f.video.id;k=b.start/L,S=A?T-y:E-p,!a&&l||!function(e,t,i,r){if(null===e)return!0;var n=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-i)>n}(l,k,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(k-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=k,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});var w=k-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 D=!!f.audio,C=!!f.video,_="";D&&(_+="audio"),C&&(_+="video");var x={data1:d,startPTS:w,startDTS:w,endPTS:P,endDTS:P,type:_,hasAudio:D,hasVideo:C,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=D&&!C?x:void 0,c.video=C?x:void 0;var M=null==m?void 0:m.sampleCount;if(M){var O=m.keyFrameIndex,F=-1!==O;x.nb=M,x.dropped=0===O||this.isVideoContiguous?0:F?O:M,x.independent=F,x.firstKeyFrame=O,F&&m.keyFrameStart&&(x.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=F),this.isVideoContiguous||(this.isVideoContiguous=F),x.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(O,"/").concat(M," dropped: ").concat(x.dropped," start: ").concat(x.firstKeyFramePTS||"NA"))}return c.initSegment=h,c.id3=Wa(i,n,l,l),r.samples.length&&(c.text=qa(r,n,l)),c}}])}(ve);function Xa(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(i?e.duration:0))/e.timescale:t}function Qa(e,t,i){var r=e.codec;if(r&&r.length>4)return r;if(t===Ce){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r){return kt(r,!1)}return i.warn('Unhandled audio codec "'.concat(r,'" in mp4 MAP')),r||"mp4a"}return i.warn('Unhandled video codec "'.concat(r,'" in mp4 MAP')),r||"avc1"}try{Ya=self.performance.now.bind(self.performance)}catch(e){Ya=Date.now}var $a=[{demux:Ea,remux:za},{demux:Ra,remux:Ka},{demux:fa,remux:Ka},{demux:pa,remux:Ka}];$a.splice(2,0,{demux:ga,remux:Ka});var Ja=function(){return o(function e(t,i,r,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=i,this.config=r,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,i,r){var n=this,a=i.transmuxing;a.executeStart=Ya();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var u=r||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,k=function(e,t){var i=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(s,t);if(k&&ar(k.method)){var S=this.getDecrypter(),A=sr(k.method);if(!S.isSync())return this.asyncResult=!0,this.decryptionPromise=S.webCryptoDecrypt(s,k.key.buffer,k.iv.buffer,A).then(function(e){var t=n.push(e,null,i);return n.decryptionPromise=null,t}),this.decryptionPromise;var b=S.softwareDecrypt(s,k.key.buffer,k.iv.buffer,A);if(i.part>-1){var L=S.flush();b=L?L.buffer:L}if(!b)return a.executeEnd=Ya(),Za(i);s=new Uint8Array(b)}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=Ya(),Za(i)}(d||h||g||I)&&this.resetInitSegment(T,m,p,E,t),(d||g||I)&&this.resetInitialTimestamp(y),c||this.resetContiguity();var w=this.transmux(s,k,v,f,i);this.asyncResult=es(w);var P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,a.executeEnd=Ya(),w}},{key:"flush",value:function(e){var t=this,i=e.transmuxing;i.executeStart=Ya();var r=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(r){var l=r.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){i.executeEnd=Ya();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(i){return t.flushRemux(s,i,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,i){var r=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(i.sn).concat(i.part>-1?" part: "+i.part:""," of ").concat(this.id===ae?"level":"track"," ").concat(i.level));var c=this.remuxer.remux(r,n,a,s,u,l,!0,this.id);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Ya()}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,i=this.remuxer;t&&i&&(t.resetTimeStamp(e),i.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,i,r,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(e,t,i,r),s.resetInitSegment(e,t,i,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,i,r,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,n):this.transmuxUnencrypted(e,i,r,n)}},{key:"transmuxUnencrypted",value:function(e,t,i,r){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,i,!1,this.id),chunkMeta:r}}},{key:"transmuxSampleAes",value:function(e,t,i,r,n){var a=this;return this.demuxer.demuxSampleAes(e,t,i).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,a.id),chunkMeta:n}})}},{key:"configureTransmuxer",value:function(e){for(var t,i=this.config,r=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(r,i,n,this.logger)),l&&l instanceof d||(this.demuxer=new d(r,i,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 Oi(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,i,r,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=i,this.initSegmentData=r,this.duration=n,this.defaultInitPts=s||null}),is=o(function e(t,i,r,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=i,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}),rs=0,ns=function(){return o(function e(t,i,r,n){var s=this;a(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=rs++,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,i=s.hls;if(i&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var r,n=null==(r=s.workerContext)?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.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,i.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=i,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=r,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(i,'"')),this.workerContext=function(e){var t=Cn[e];if(t)return t.clientCount++,t;var i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Cn[e]=r,r}(o.workerPath)):(c.log('injecting Web Worker for "'.concat(i,'"')),this.workerContext=function(){var e=Cn[Dn];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"}),i=self.URL.createObjectURL(t),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return Cn[Dn]=r,r}());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:i,config:Kt(o)})}catch(e){c.warn('Error setting up "'.concat(i,'" Web Worker, fallback to inline'),e),this.terminateWorker(),this.error=null,this.transmuxer=new Ja(this.observer,u,o,"",i,t.logger)}return}}this.transmuxer=new Ja(this.observer,u,o,"",i,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=rs++;var t=this.hls.config,i=Lt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,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=Cn[e||Dn];if(t&&1===t.clientCount--){var i=t.worker,r=t.objectURL;delete Cn[e||Dn],r&&self.URL.revokeObjectURL(r),i.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,i,r,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,m=n.decryptdata,p=this.frag,y=!(p&&n.cc===p.cc),E=!(p&&l.level===p.level),T=p?l.sn-p.sn:-1,k=this.part?l.part-this.part.index:-1,S=0===T&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!E&&(1===T||0===T&&(1===k||S&&k<=0)),b=self.performance.now();(E||T||0===n.stats.parsing.start)&&(n.stats.parsing.start=b),!a||!k&&A||(a.stats.parsing.start=b);var L=!(p&&(null==(c=n.initSegment)?void 0:c.url)===(null==(d=p.initSegment)?void 0:d.url)),I=new is(y,A,o,E,g,L);if(!A||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(A,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(L));var R=new ts(i,r,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:m,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(v){var w=v.push(e,m,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 i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:e});else if(r){var n=r.flush(e);es(n)?n.then(function(i){t.handleFlushResult(i,e)}).catch(function(i){t.transmuxerError(i,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}},{key:"transmuxerError",value:function(e,t,i){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:i}))}},{key:"handleFlushResult",value:function(e,t){var i=this;e.forEach(function(e){i.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),as=function(e){function t(e,i,r){var s;return a(this,t),(s=n(this,t,[e,i,r,"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 i=t.frag,r=t.id,n=t.initPTS,a=t.timescale,s=t.trackId;if(r===ae){var o=i.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=i,this.state===kn){var u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==o)&&this.syncWithAnchor(i,null==u?void 0:u.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(i,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 i,r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(!t||(null==r?void 0:r.cc)!==t.cc){var n=(r||e).cc,a=ri(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 i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @".concat(i.toFixed(3))),e=i,this.state=hn):this.state=mn,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 mn:var e=this.levels,i=this.trackId,r=null==e?void 0:e[i],n=null==r?void 0:r.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=kn}break;case gn:this.checkRetryDate();break;case kn: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,i=this.levels,r=this.media,n=this.trackId,a=t.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=i&&i[n]){var s=i[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=mn,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Ce,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&&r){var m=v;o.PTSKnown&&m<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var p=this.getNextFragment(g,o);if(p&&this.isLoopLoading(p,g)&&(p=this.getNextFragmentLoopLoading(p,o,u,ae,d)),p){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Oe(p)&&!p.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Li&&(this.mainFragLoading=y=null),y&&Oe(y))){if(p.start>y.end){var E=this.fragmentTracker.getFragAtPos(g,ae);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,s,g)}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(e,i){this.bufferFlushed=this.flushing=!1,E(t,"onMediaDetaching",this,3)([e,i])}},{key:"onAudioTracksUpdated",value:function(e,t){var i=t.audioTracks;this.resetTransmuxer(),this.levels=i.map(function(e){return new Gt(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var i=!!t.url;this.trackId=t.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(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 i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ee.AUDIO_TRACK_LOADED,i))}},{key:"onAudioTrackLoaded",value:function(e,t){var i,r=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(r){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==dn&&(this.state=mn));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=r[a],c=0;if(n.live||null!=(i=u.details)&&i.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!==mn||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,i=e.frag,r=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(i.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[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==h){var v=r?r.index:-1,g=-1!==v,m=new Hi(i.level,i.sn,i.stats.chunkCount,n.byteLength,v,g);d.push(n,f,c,"",i,r,u.totalduration,!1,m,h)}else{this.log("Unknown video PTS for cc ".concat(i.cc,", waiting for video PTS before demuxing audio frag ").concat(i.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new Ln,complete:!1}).cache.push(new Uint8Array(n)),this.state!==dn&&(this.state=kn)}}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(i.sn," of level ").concat(i.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 i=t.tracks.audio;i&&(this.mediaBuffer=i.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 i=t.frag,r=t.part;if(i.type===se)if(this.fragContextChanged(i))this.warn("Fragment ".concat(i.sn).concat(r?" p: "+r.index:""," of level ").concat(i.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if(Oe(i)){this.fragPrevious=i;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},n)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==ae||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"onError",value:function(e,i){var r;if(i.fatal)this.state=Tn;else switch(i.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,i);break;case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==mn||(null==(r=i.context)?void 0:r.type)!==re||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)||this.resetLoadingState();break;case Z.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,E(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]));break;case Z.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==_e&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var i=t.type;if(i!==_e){this.flushing=!1,this.bufferFlushed=!0,this.state===En&&(this.state=hn);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,se),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var t,i="audio",r=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=pn,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),r.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:i,tracks:v.tracks})}if(d){var m=d.startPTS,p=d.endPTS,y=d.startDTS,E=d.endDTS;l&&(l.elementaryStreams[Ce]={startPTS:m,endPTS:p,startDTS:y,endDTS:E}),o.setElementaryStreamInfo(Ce,m,p,y,E),this.bufferFragmentData(d,o,l,a)}if(null!=f&&null!=(t=f.samples)&&t.length){var T=de({id:i,frag:o,details:c},f);r.trigger(ee.FRAG_PARSING_METADATA,T)}if(h){var k=de({id:i,frag:o,details:c},h);r.trigger(ee.FRAG_PARSING_USERDATA,k)}}else this.fragmentTracker.removeFragment(o)}else this.resetWhenMissingContext(a)}},{key:"_bufferInitSegment",value:function(e,t,i,r){if(this.state===pn&&(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:i,part:null,chunkMeta:r,parent:i.type,data:s};this.hls.trigger(ee.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,i,r){var n,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===Si||a===bi)if(Oe(e))if(null!=(n=i.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=kn;var s=this.mainDetails;s&&s.fragmentStart!==i.details.fragmentStart&&on(i.details,s)}else E(t,"loadFragment",this,3)([e,i,r]);else this._loadInitSegment(e,i);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;zt({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.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))}}])}(An),ss=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[i,e.logger])).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=e,r}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,i){var r=null==t?void 0:t.renditionReports;if(r){for(var n=-1,a=0;a<r.length;a++){var s=r[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=r[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=i&&Bt(i);return new Ut(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,i){var r=t.details,n=t.stats,a=self.performance.now(),s=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-s;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach(function(e){e.setStart(e.playlistOffset+l)})}if(r.live||null!=i&&i.live){var u="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){Wr(i,r,this);var c=r.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:r.url,error:c,reason:c.message,level:t.level||void 0,parent:null==(h=r.fragments[0])?void 0:h.type,networkDetails:f,stats:n})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=n.loading.start);var v,g=this.hls.mainForwardBufferInfo,m=g?g.end-g.len:0,p=Xr(r,1e3*(r.edge-m));if(r.requestScheduled+p<a?r.requestScheduled=a:r.requestScheduled+=p,this.log("live playlist ".concat(e," ").concat(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var T=this.hls.config.lowLatencyMode,k=r.lastPartSn,S=r.endSN,A=r.lastPartIndex,b=k===S;-1!==A?b?(y=S+1,E=T?0:A):(y=k,E=T?A+1:r.maxPartIndex):y=S+1;var L=r.age,I=L+r.ageHeader,R=Math.min(I-r.partTarget,1.5*r.targetduration);if(R>0){if(I>3*r.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!=i&&i.tuneInGoal&&I-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(i.tuneInGoal," to: ").concat(R," with playlist age: ").concat(r.age)),R=0;else{var w=Math.floor(R/r.targetduration);if(y+=w,void 0!==E)E+=Math.round(R%r.targetduration/r.partTarget);this.log("CDN Tune-in age: ".concat(r.ageHeader,"s last advanced ").concat(L.toFixed(2),"s goal: ").concat(R," skip sn ").concat(w," to part ").concat(E))}r.tuneInGoal=R}if(v=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E),T||!b)return r.requestScheduled=a,void this.loadingPlaylist(u,v)}else(r.canBlockReload||r.canSkipUntil)&&(v=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E));v&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(p-2*s,p/2)),this.scheduleLoading(u,v,r)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,i){var r=this,n=i||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 r.loadingPlaylist(e,t)},o)}}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,i,r){var n=Bt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=Ot),new Ut(i,r,n)}},{key:"checkRetry",value:function(e){var t=this,i=e.details,r=ni(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===gi||!n.resolved&&s===fi);if(c){var d;if(l>=u.maxNumRetry)return!1;if(r&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(i,'" without delivery-directives')),this.loadPlaylist();else{var h=li(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(i,'" 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 i=0;i<e.length;i++)if(!ls(e[i].attrs,t[i].attrs))return!1;return!0}function ls(e,t,i){var r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(i){return e[i]!==t[i]})}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 i;return a(this,t),(i=n(this,t,[e,"audio-track-controller"])).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,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_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 i=t.id,r=t.groupId,n=t.details,a=this.tracksInGroup[i];if(a&&a.groupId===r){var s=a.details;a.details=t.details,this.log("Audio track ".concat(i,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(r," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),i===this.trackId&&this.playlistLoaded(i,t,s)}else this.warn("Audio track with id:".concat(i," and group:").concat(r," 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 i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(function(e){return-1===(null==r?void 0:r.indexOf(e))})){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!i||-1!==i.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=Yt(s,a,Xt);if(o>-1)n=a[o];else{var l=Yt(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==i?void 0:i.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!==re||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 i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&zt(e,r,Xt))return r;var n=Yt(e,this.tracksInGroup,Xt);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n),a}if(r){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,i,r,n){var a=t[r],s=t.reduce(function(e,t,i){var r=t.uri;return(e[r]||(e[r]=[])).push(i),e},{})[a.uri];s.length>1&&(r=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),c=Qt(t,r,function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var r=t.audioGroups,a=i.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});return Yt(e,a,n)>-1});return c>-1?c:Qt(t,r,function(t){var r=t.audioGroups,a=i.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});return Yt(e,a,n)>-1})}(e,t.levels,i,s,Xt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=Yt(e,i);if(l>-1)return i[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 i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(!(e===this.trackId&&r===i&&n||(this.log("Switching to audio-track ".concat(e,' "').concat(r.name,'" lang:').concat(r.lang," group:").concat(r.groupId," channels:").concat(r.channels)),this.trackId=e,this.currentTrack=r,this.hls.trigger(ee.AUDIO_TRACK_SWITCHING,fe({},r)),n))){var a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,i=0;i<t.length;i++){var r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||zt(e,r,Xt)))return i}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 i=this.currentTrack;this.shouldLoadPlaylist(i)&&$t(i.url,this.hls)&&this.scheduleLoading(i,e)}},{key:"loadingPlaylist",value:function(e,i){E(t,"loadingPlaylist",this,3)([e,i]);var r=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,i),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(r,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.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:r,groupId:n,deliveryDirectives:i||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,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(r,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(i){if(t.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(r)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(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 i=t[0];try{i.execute()}catch(t){var r;if(i.onError(t),null===this.queues||null===this.tracks)return;var n=null==(r=this.tracks[e])?void 0:r.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,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?"SourceBuffer".concat(r.updating?" updating":"").concat(i.ended?" ended":"").concat(i.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 i;return a(this,t),(i=n(this,t,[e])).name=fs,i}return d(t,e),o(t)}(L(Error)),gs=function(e){function t(e,i){var r,s;return a(this,t),(r=n(this,t,["buffer-controller",e.logger])).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(e){var t;r.hls&&"open"===(null==(t=r.mediaSource)?void 0:t.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(e){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(e){var t=r,i=t.media,n=t.mediaSource;e&&r.log("Media source opened"),i&&n&&(n.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(ee.MEDIA_ATTACHED,{media:i,mediaSource:n}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var e=r,t=e.mediaSrc,i=e._objectUrl;t!==i&&r.error("Media element src was set while attaching MediaSource (".concat(i," > ").concat(t,")"))},r.hls=e,r.fragmentTracker=i,r.appendSource=(s=ke(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),r.initTracks(),r.registerListeners(),r}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,i=this.mediaSource;if(!t)return null;var r={};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===i?de(r,s.tracks):this.sourceBuffers.forEach(function(t){var i=p(t,1)[0];i&&(r[i]=de({},e.tracks[i]),e.removeBuffer(i)),t[0]=t[1]=null}),{media:t,mediaSource:i,tracks:r}}},{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 i,r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log("".concat(r," bufferCodec event(s) expected.")),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var i=this.media=t.media;this.transferData=this.overrides=void 0;var r=ke(this.appendSource);if(r){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&a instanceof o,ms(i),function(e,t){var i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,s),i.load()}catch(e){i.src=s}else i.src=s}i.addEventListener("emptied",this._onMediaEmptied)}}},{key:"assignMediaSource",value:function(e){var t,i;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(i=e.constructor)?void 0:i.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,i=this.transferData;if(i&&t){var r=this.tracks,n=i.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(r,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,r)){i.mediaSource=null,i.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(r),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(ee.MEDIA_DETACHING,{}),this.onMediaAttaching(ee.MEDIA_ATTACHING,i),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var i=t,r=n[i];if(r){var a=r.buffer;if(a){var s=e.fragmentTracker,o=r.id;if(s.hasFragments(o)||s.hasParts(o)){var l=ji.getBuffered(a);s.detectEvictedFragments(i,l,o,null,!0)}var u=ps(i),c=[i,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(i),e.trackSourceBuffer(i,r)}}}),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 i=this,r=!!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(r?"transferring":"detaching")),r)this.sourceBuffers.forEach(function(e){var t=p(e,1)[0];t&&i.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),r||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&ms(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 i=p(t,1)[0];i&&e.resetBuffer(i)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn("onBufferReset ".concat(e),t)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[ps(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 i,r=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 i,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==(i=r.transferData)||null==(i=i.tracks)?void 0:i[e],g=null!=v&&v.buffer?v:f,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=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(m,p),E=null==y?void 0:y.replace(hs,"$1"),T=St(l,u),k=null==(a=T)?void 0:a.replace(hs,"$1");T&&y&&E!==k&&("audio"===e.slice(0,5)&&(T=kt(T,r.appendSource)),r.log("switching codec ".concat(m," to ").concat(T)),T!==(f.pendingCodec||f.codec)&&(f.pendingCodec=T),f.container=c,r.appendChangeType(e,c,T))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(i=t.audio)?void 0:i.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,i){var r=e.tracks[i];return t[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,i){var r=this,n="".concat(t,";codecs=").concat(i),a={label:"change-type=".concat(n),execute:function(){var a=r.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(r.log("changing ".concat(e," sourceBuffer type to ").concat(n)),s.changeType(n),a.codec=i,a.container=t)}r.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.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,i=this,r=e.start,n=r+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(r,ae))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t=i.tracks.video;(i.lastVideoAppendEnd>n||null!=t&&t.buffer&&ji.isBuffered(t.buffer,n)||!0===(null==(e=i.fragmentTracker.getAppendedFrag(n,ae))?void 0:e.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){i.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 i=this,r=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,m=l?l.stats.buffering:null;0===g.start&&(g.start=v),m&&0===m.start&&(m.start=v);var y=r.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 T=r.video,k=null==T?void 0:T.buffer;if(k&&"initSegment"!==h){var S=l||o,A=this.blockedAudioAppend;if("audio"!==a||"main"===s||this.blockedAudioAppend||T.ending||T.ended){if("video"===a){var b=S.end;if(A){var L=A.frag.start;(b>L||b<this.lastVideoAppendEnd||ji.isBuffered(k,L))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}else{var I=S.start+.05*S.duration,R=k.buffered,w=this.currentOp("video");R.length||w?!w&&!ji.isBuffered(k,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(S):this.blockAudio(S)}}var P=(l||o).start,D={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=i.tracks[a])?void 0:e.buffer;t&&(E?i.updateTimestampOffset(t,P,.1,a,h,f):void 0!==c&&X(c)&&i.updateTimestampOffset(t,c,1e-6,a,h,f)),i.appendExecutor(n,a)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),m&&0===m.first&&(m.first=e);var t={};i.sourceBuffers.forEach(function(e){var i=p(e,2),r=i[0],n=i[1];r&&(t[r]=ji.getBuffered(n))}),i.appendErrors[a]=0,"audio"===a||"video"===a?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(ee.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:o.type,timeRanges:t})},onError:function(e){var t,r={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=i.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)r.details=Z.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!n)r.errorAction=ki(!0);else if(e.name===fs&&0===i.sourceBufferCount)r.errorAction=ki(!0);else{var s=++i.appendErrors[a];i.warn("Failed ".concat(s,"/").concat(i.hls.config.appendErrorMaxRetry,' times to append segment in "').concat(a,'" sourceBuffer (').concat(n||"no media error",")")),(s>=i.hls.config.appendErrorMaxRetry||n)&&(r.fatal=!0)}i.hls.trigger(ee.ERROR,r)}};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(D,a,this.isPending(this.tracks[a]))}},{key:"getFlushOp",value:function(e,t,i){var r=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(i)),{label:"remove",execute:function(){r.removeExecutor(e,t,i)},onStart:function(){},onComplete:function(){r.hls.trigger(ee.BUFFER_FLUSHED,{type:e})},onError:function(n){r.warn("Failed to remove ".concat(t,"-").concat(i,' from "').concat(e,'" SourceBuffer'),n)}}}},{key:"onBufferFlushing",value:function(e,t){var i=this,r=t.type,n=t.startOffset,a=t.endOffset;r?this.append(this.getFlushOp(r,n,a),r):this.sourceBuffers.forEach(function(e){var t=p(e,1)[0];t&&i.append(i.getFlushOp(t,n,a),t)})}},{key:"onFragParsed",value:function(e,t){var i=this,r=t.frag,n=t.part,a=[],s=n?n.elementaryStreams:r.elementaryStreams;s[xe]?a.push("audiovideo"):(s[Ce]&&a.push("audio"),s[_e]&&a.push("video"));0===a.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(r.type," level: ").concat(r.level," sn: ").concat(r.sn)),this.blockBuffers(function(){var e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:r.stats;i.hls.trigger(ee.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})},a).catch(function(e){i.warn("Fragment buffered callback ".concat(e)),i.stepOperationQueue(i.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 i=p(t,1)[0];if(i){var r=e.tracks[i];if(r)return!r.ended||r.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var i,r=this;this.sourceBuffers.forEach(function(e){var i=p(e,1)[0];if(i){var n=r.tracks[i];t.type&&t.type!==i||(n.ending=!0,n.ended||(n.ended=!0,r.log("".concat(i," buffer reached EOS"))))}});var n=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,i=p(e,1)[0];return i&&!(null!=(t=r.tracks[i])&&t.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(function(){r.tracksEnded();var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream(),r.hls.trigger(ee.BUFFERED_TO_END,void 0)):e&&r.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 i=p(t,1)[0];if(null!==i){var r=e.tracks[i];r&&(r.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var i=t.details;i.fragments.length&&(this.details=i,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 i,r=null==(i=t.errorAction)?void 0:i.nextAutoLevel;X(r)&&r!==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,i=this.media;if(i&&null!==t&&this.sourceBufferCount){var r=e.config,n=i.currentTime,a=t.levelTargetDuration,s=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.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=r.frontBufferFlushThreshold;if(X(u)&&u>0){var c=Math.max(r.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,i){var r=this;this.sourceBuffers.forEach(function(e){var t=p(e,2),n=t[0],a=t[1];if(a){var s=ji.getBuffered(a);if(s.length>0&&i>s.start(0)){var o;r.hls.trigger(ee.BACK_BUFFER_REACHED,{bufferEnd:i});var l=r.tracks[n];if(null!=(o=r.details)&&o.live)r.hls.trigger(ee.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=l&&l.ended)return void r.log("Cannot flush ".concat(n," back buffer while SourceBuffer is in ended state"));r.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}},{key:"flushFrontBuffer",value:function(e,t,i){var r=this;this.sourceBuffers.forEach(function(t){var n=p(t,2),a=n[0],s=n[1];if(s){var o=ji.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(i>u||e>=u&&e<=c)return;r.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,i=this.mediaSource;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,r)}}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 r>(X(i.duration)?i.duration:0)&&r>s||!X(s)?{duration:r}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,i=e.start,r=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!==i&&void 0!==r&&(this.log("MediaSource duration is set to ".concat(n.duration,". Setting seekable range to ").concat(i,"-").concat(r,".")),n.setLiveSeekableRange(i,r)))}},{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,i=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(Kt(i))),this.tracksReady){var r,n=null==(r=this.transferData)?void 0:r.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(i){var r=p(i,2),n=r[0],a=r[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 i=p(t,1)[0];e.executeNext(i)})}else{var i=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:i,reason:i.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in e){var n=r,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=i.addSourceBuffer(o),u=ps(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 i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&vt(i,"video")&&(r=function(e,t){var i=[];if(e)for(var r=e.split(","),n=0;n<r.length;n++)ft(r[n],"video")||i.push(r[n]);return t&&i.push(t),i.join(",")}(r,i));var n=St(r,e.levelCodec);return n?"audio"===t.slice(0,5)?kt(n,this.appendSource):n:""}},{key:"trackSourceBuffer",value:function(e,t){var i=this,r=t.buffer;if(r){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,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 r=t.removedRanges;null!=r&&r.length&&i.hls.trigger(ee.BUFFER_FLUSHED,{type:e})})}}},{key:"mediaSrc",get:function(){var e,t,i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.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 i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var i,r=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(null==(i=this.mediaSource)?void 0:i.readyState));this.error("".concat(r),t),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});var n=this.currentOp(e);n&&n.onError(r)}},{key:"updateTimestampOffset",value:function(e,t,i,r,n,a){var s=t-e.timestampOffset;Math.abs(s)>=i&&(this.log("Updating ".concat(r," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(n," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,i){var r=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!r||!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(r.duration)?r.duration:1/0,l=X(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(i,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 i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new vs("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));i.ending=!1,i.ended=!1,r.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=p(e,2),i=t[0],r=t[1];return i&&r.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var i=p(t,1)[0];return i&&!!e.currentOp(i)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"blockBuffers",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!i.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var r=this.operationQueue,n=i.map(function(e){return t.appendBlocker(e)});return i.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(function(i){r===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var i,r=null==(i=t.tracks[e])?void 0:i.buffer;r&&!r.updating&&t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}},{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,i){return t+(e.isPending(e.tracks[i])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(p(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return p(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,i){var r=this.tracks[e];if(r){var n=r.buffer;if(n){var a=i.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var i=t.buffer;i&&(t.listeners.forEach(function(e){i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}}])}(ve);function ms(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function ps(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 i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.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 i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.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,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(i,": ").concat(e[i].height,"p@").concat(e[i].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(t){var i=this,r=this.hls.levels;if(!r.length)return-1;var n=r.filter(function(e,r){return i.isLevelAllowed(e)&&r<=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 i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.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,i){if(null==e||!e.length)return-1;for(var r=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=Math.max(t,i),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&r(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"},Ts={HLS:"h"},ks=o(function e(t,i){a(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=i});function Ss(e,t,i,r){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(i),{cause:r});var n}function As(e,t,i){return Ss("serialize",e,t,i)}var bs=o(function e(t){a(this,e),this.description=t}),Ls="Bare Item";function Is(e){if(!1===ArrayBuffer.isView(e))throw As(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,T(t)))),":");var t}function Rs(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw As(e,"Integer");return e.toString()}function ws(e,t){if(e<0)return-ws(-e,t);var i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){var r=Math.floor(e*i);return(r%2==0?r:r+1)/i}return Math.round(e*i)/i}function Ps(e){var t=ws(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw As(e,"Decimal");var i=t.toString();return i.includes(".")?i:"".concat(i,".0")}var Ds=/[\x00-\x1f\x7f]+/;function Cs(e){var t,i=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw As(i,"Token");return i}function _s(e){switch(S(e)){case"number":if(!X(e))throw As(e,Ls);return Number.isInteger(e)?Rs(e):Ps(e);case"string":return function(e){if(Ds.test(e))throw As(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return Cs(e);case"boolean":return function(e){if("boolean"!=typeof e)throw As(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 bs)return Cs(e);default:throw As(e,Ls)}}function xs(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw As(e,"Key");return e}function Ms(e){return null==e?"":Object.entries(e).map(function(e){var t=p(e,2),i=t[0],r=t[1];return!0===r?";".concat(xs(i)):";".concat(xs(i),"=").concat(_s(r))}).join("")}function Os(e){return e instanceof ks?"".concat(_s(e.value)).concat(Ms(e.params)):_s(e)}function Fs(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==S(e)||null==e)throw As(e,"Dict");var i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map(function(e){var t=p(e,2),i=t[0],r=t[1];r instanceof ks==!1&&(r=new ks(r));var n,a=xs(i);return!0===r.value?a+=Ms(r.params):(a+="=",Array.isArray(r.value)?a+="(".concat((n=r).value.map(Os).join(" "),")").concat(Ms(n.params)):a+=Os(r)),a}).join(",".concat(r))}function Ns(e,t){return Fs(e,t)}var Bs="CMCD-Object",Us="CMCD-Request",Gs="CMCD-Session",Vs="CMCD-Status",Hs={br:Bs,ab:Bs,d:Bs,ot:Bs,tb:Bs,tpb:Bs,lb:Bs,tab:Bs,lab:Bs,url:Bs,pb:Us,bl:Us,tbl:Us,dl:Us,ltc:Us,mtp:Us,nor:Us,nrr:Us,rc:Us,sn:Us,sta:Us,su:Us,ttfb:Us,ttfbb:Us,ttlb:Us,cmsdd:Us,cmsds:Us,smrt:Us,df:Us,cs:Us,ts:Us,cid:Gs,pr:Gs,sf:Gs,sid:Gs,st:Gs,v:Gs,msd:Gs,bs:Vs,bsd:Vs,cdn:Vs,rtp:Vs,bg:Vs,pt:Vs,ec:Vs,e:Vs},Ks=Us;function js(e,t){var i={};if(!e)return i;var r,n=Object.keys(e),a=t?(r=t,Object.keys(r).reduce(function(e,t){var i;return null===(i=r[t])||void 0===i||i.forEach(function(i){return e[i]=t}),e},{})):{};return n.reduce(function(t,i){var r,n=Hs[i]||a[i]||Ks;return(null!==(r=t[n])&&void 0!==r?r:t[n]={})[i]=e[i],t},i)}var Ws="event";var qs=function(e){return Math.round(e)},Ys=function(e,t){return Array.isArray(e)?e.map(function(e){return Ys(e,t)}):e instanceof ks&&"string"==typeof e.value?new ks(Ys(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;for(var n=i.pathname.split("/").slice(1),a=r.pathname.split("/").slice(1,-1);n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},zs=function(e){return 100*qs(e/100)},Xs={br:qs,d:qs,bl:zs,dl:zs,mtp:zs,nor:function(e,t){var i=e;return t.version>=2&&(e instanceof ks&&"string"==typeof e.value?i=new ks([e]):"string"==typeof e&&(i=[e])),Ys(i,t)},rtp:zs,tb:qs},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 io=["d","dl","nor","ot","rtp","su"];var ro=["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)||io.includes(e)||ro.includes(e)||to(e)}),Ws,function(e){return Js.includes(e)||Zs.includes(e)||to(e)}),Qs,function(e){return Js.includes(e)||io.includes(e)||to(e)});function oo(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};if(null==e||"object"!==S(e))return i;var r=t.version||e.v||1,n=t.reportingMode||Qs,a=1===r?ao:so[n],s=Object.keys(e).filter(a),o=t.filter;"function"==typeof o&&(s=s.filter(o));var l=n===$s||n===Ws;l&&!s.includes("ts")&&s.push("ts"),r>1&&!s.includes("v")&&s.push("v");var u=de({},Xs,t.formatters),c={version:r,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===r)return;n=r}"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 bs(n)),i[t]=n))}),i}function lo(e,t,i){return de(e,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};if(!e)return i;var r=js(oo(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(r).reduce(function(e,t){var i=p(t,2),r=i[0],n=Ns(i[1],{whitespace:!1});return n&&(e[r]=n),e},i)}(t,i))}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,i){var r=function(e){if(!e)return"";var t=uo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return"".concat("CMCD","=").concat(t)}(t,i);if(!r)return e;if(co.test(e))return e.replace(co,r);var n=e.includes("?")?"&":"?";return"".concat(e).concat(n).concat(r)}var fo=function(){return o(function e(t){var i=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(){i.initialized&&(i.starved=!0),i.buffering=!0},this.onPlaying=function(){i.initialized||(i.initialized=!0),i.buffering=!1},this.applyPlaylistData=function(e){try{i.apply(e,{ot:Es.MANIFEST,su:!i.initialized})}catch(e){i.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var t=e.frag,r=e.part,n=i.hls.levels[t.level],a=i.getObjectType(t),s={d:1e3*(r||t).duration,ot:a};a!==Es.VIDEO&&a!==Es.AUDIO&&a!=Es.MUXED||(s.br=n.bitrate/1e3,s.tb=i.getTopBandwidth(a)/1e3,s.bl=i.getBufferLength(a));var o=r?i.getNextPart(r):i.getNextFrag(t);null!=o&&o.url&&o.url!==t.url&&(s.nor=o.url),i.apply(e,s)}catch(e){i.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=t;var r=this.config=t.config,n=r.cmcd;null!=n&&(r.pLoader=this.createPlaylistLoader(),r.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 i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}},{key:"createData",value:function(){var e;return{v:1,sf:Ts.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 i=t.ot===Es.INIT||t.ot===Es.VIDEO||t.ot===Es.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var r=this.includeKeys;r&&(t=Object.keys(t).reduce(function(e,i){return r.includes(i)&&(e[i]=t[i]),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,i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){var r=e.sn-i.startSN;return i.fragments[r+1]}}},{key:"getNextPart",value:function(e){var t,i=e.index,r=e.fragment,n=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=r.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===i&&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,i=0,r=this.hls;if(e===Es.AUDIO)t=r.audioTracks;else{var n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;t=r.levels.slice(0,a)}return t.forEach(function(e){e.bitrate>i&&(i=e.bitrate)}),i>0?i:NaN}},{key:"getBufferLength",value:function(e){var t=this.media,i=e===Es.AUDIO?this.audioBuffer:this.videoBuffer;return i&&t?1e3*ji.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,i=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new i(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,i,r){t(e),this.loader.load(e,i,r)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,i=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new i(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,i,r){t(e),this.loader.load(e,i,r)}}])}()}}])}(),vo=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["content-steering",e.logger])).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=e,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.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 i=t.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.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 i=t.errorAction;if((null==i?void 0:i.action)===fi&&i.flags===pi){var r=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&&r?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),t.details!==Z.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(r?r.length:r," priorities: ").concat(Kt(n)," penalized: ").concat(Kt(this.penalizedPathways))):i.resolved=!0}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var i=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(i,'"')),t=this.getLevelsForPathway(i),this.pathwayId=i}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 i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(function(e){r-i[e]>3e5&&delete i[e]});for(var n=0;n<e.length;n++){var a=e[n];if(!(a in i)){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,Zr(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,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),n=0;n<r.length;n++)if(t===re&&r[n].hasAudioGroup(e)||t===ne&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}},{key:"clonePathways",value:function(e){var t=this,i=this.levels;if(i){var r={},n={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!i.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new Ji(e.attrs);t["PATHWAY-ID"]=a;var i=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);i&&(r[t.AUDIO]=i,t.AUDIO=i),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=mo(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});i.push.apply(i,T(l)),go(t.audioTracks,r,o,a),go(t.subtitleTracks,n,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,i=this,r=this.hls.config,n=r.loader;this.loader&&this.loader.destroy(),this.loader=new n(r);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||r.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+a)}var s={responseType:"json",url:t.href},o=r.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,r,n,a){i.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){i.updated=performance.now(),i.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,t).href}catch(e){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}i.scheduleRefresh(i.uri||n.url),l&&i.clonePathways(l);var c={steeringManifest:s,url:t.toString()};i.hls.trigger(ee.STEERING_MANIFEST_LOADED,c),u&&i.updatePathwayPriority(u)}else i.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,r,n){if(i.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),i.stopLoad(),410===e.code)return i.enabled=!1,void i.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*i.timeToLoad;if(429!==e.code)i.scheduleRefresh(i.uri||t.url,a);else{var s=i.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}i.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,r){i.log("Timeout loading steering manifest (".concat(t.url,")")),i.scheduleRefresh(i.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var i,r=null==(i=t.hls)?void 0:i.media;!r||r.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},i)}}])}(ve);function go(e,t,i,r){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 Ji(a.attrs),a.url=a.attrs.URI=mo(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=r,a});e.push.apply(e,T(a))})}function mo(e,t,i,r){var n,a=r.HOST,s=r.PARAMS,o=r[i];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 po=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["eme",e.logger])).hls=void 0,i.config=void 0,i.media=null,i.mediaResolved=void 0,i.keyFormatPromise=null,i.keySystemAccessPromises={},i._requestLicenseFailureCount=0,i.mediaKeySessions=[],i.keyIdToKeySessionPromise={},i.mediaKeys=null,i.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],i.bannedKeyIds={},i.onMediaEncrypted=function(e){var t=e.initDataType,r=e.initData,n='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(i.debug(n),null!==r){if(!i.keyFormatPromise){var a=Object.keys(i.keySystemAccessPromises);a.length||(a=Er(i.config));var s=a.map(yr).filter(function(e){return!!e});i.keyFormatPromise=i.getKeyFormatPromise(s)}i.keyFormatPromise.then(function(a){var s=pr(a);if("sinf"===t&&s===hr.FAIRPLAY){var o;try{var l=He(new Uint8Array(r)),u=it(or(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 i.warn("".concat(n," Failed to parse sinf: ").concat(e))}for(var c,d=be(o),h=i,f=h.keyIdToKeySessionPromise,v=h.mediaKeySessions,g=f[d],m=function(){var e=v[p],n=e.decryptdata;if(!n.keyId)return 0;var a=be(n.keyId);return rr(o,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(d)?(g=f[a])?(n.pssh||(delete f[a],n.pssh=new Uint8Array(r),n.keyId=o,(g=f[d]=g.then(function(){return i.generateRequestWithPreferredKeySession(e,t,r,"encrypted-event-key-match")})).catch(function(e){return i.handleError(e)})),1):0:void 0},p=0;p<v.length&&(0===(c=m())||1!==c);p++);g||i.handleError(new Error("Key ID ".concat(d," not encountered in playlist. Key-system sessions ").concat(v.length,".")))}else i.log('Ignoring "'.concat(e.type,'" event with init data type: "').concat(t,'" for selected key-system ').concat(s))}).catch(function(e){return i.handleError(e)})}},i.onWaitingForKey=function(e){i.log('"'.concat(e.type,'" event'))},i.hls=e,i.config=e.config,i.registerListeners(),i}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,i=t.drmSystems,r=t.widevineLicenseUrl,n=null==i?void 0:i[e];return n?n.licenseUrl:e===hr.WIDEVINE&&r?r: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,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]'))}},{key:"attemptKeySystemAccess",value:function(e){var t=this,i=this.hls.levels,r=function(e,t,i){return!!e&&i.indexOf(e)===t},n=i.map(function(e){return e.audioCodec}).filter(r),a=i.map(function(e){return e.videoCodec}).filter(r);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(i,r){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then(function(e){return i({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):r(t instanceof To?t:new To({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 i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function ".concat(i);return null===kr&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(r))}return i(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,i){var r,n=this,a=function(e,t,i,r){var n;switch(e){case hr.FAIRPLAY:n=["cenc","sinf"];break;case hr.WIDEVINE:case hr.PLAYREADY:n=["cenc"];break;case hr.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}}),videoCapabilities:i.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}})}]}(n,t,i,r)}(e,t,i,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(r=s)?void 0:r.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 i=n.fetchServerCertificate(e);n.log('Create media-keys for "'.concat(e,'"'));var r=l.mediaKeys=t.createMediaKeys().then(function(t){return n.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,i.then(function(i){return i?n.setMediaKeysServerCertificate(t,e,i):t})});return r.catch(function(t){n.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),r})}return o.then(function(){return s.mediaKeys})}},{key:"createMediaKeySessionContext",value:function(e){var t=e.decryptdata,i=e.keySystem,r=e.mediaKeys;this.log('Creating key-system session "'.concat(i,'" keyId: ').concat(be(t.keyId||[])," keyUri: ").concat(t.uri));var n=r.createSession(),a={decryptdata:t,keySystem:i,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}},{key:"renewKeySession",value:function(e){var t=e.decryptdata;if(t.pssh){var i=this.createMediaKeySessionContext(e),r=yo(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"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 i=e.mediaKeysSession;return this.log('Updating key-session "'.concat(i.sessionId,'" for keyId ').concat(be(e.decryptdata.keyId||[]),"\n } (data length: ").concat(t.byteLength,")")),i.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 yr(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var i=e.keySystem,r=e.mediaKeys;return t.attemptSetMediaKeys(i,r)})}},{key:"selectKeySystem",value:function(e){var t=this;return new Promise(function(i,r){t.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,n=yr(t);n?i(n):r(new Error('Unable to find format for key-system "'.concat(t,'"')))}).catch(r)})}},{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=Er(this.config),i=e.map(pr).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(i)}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,i=0;i<t.length;i++){var r=Eo(e,t[i]);if(r)return r}}},{key:"loadKey",value:function(e){var t=this,i=e.keyInfo.decryptdata,r=yo(i),n=this.bannedKeyIds[r];if(n||"internal-error"===this.getKeyStatus(i)){var a=ko(n||"internal-error",i);return this.handleError(a,e.frag),Promise.reject(a)}var s="(keyId: ".concat(r,' format: "').concat(i.keyFormat,'" method: ').concat(i.method," uri: ").concat(i.uri,")");this.log("Starting session for key ".concat(s));var o=this.keyIdToKeySessionPromise[r];if(!o){var l=this.getKeySystemForKeyPromise(i).then(function(r){var n=r.keySystem,a=r.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:i})})}).then(function(e){var r=i.pssh?i.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")});return l.catch(function(i){return t.handleError(i,e.frag)}),this.keyIdToKeySessionPromise[r]=l,l}return o.catch(function(r){if(r instanceof To){var n=fe({},r.data);"internal-error"===t.getKeyStatus(i)&&(n.decryptdata=i);var a=new To(n,r.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 To){t&&(e.data.frag=t);var i=e.data.decryptdata;this.error("".concat(e.message).concat(i?" (".concat(be(i.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),i=this.keyIdToKeySessionPromise[t];if(!i){var r=pr(e.keyFormat),n=r?[r]:Er(this.config);return this.attemptKeySystemAccess(n)}return i}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=Er(this.config)),0===e.length)throw new To({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 i=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var n=Promise.all(r).then(function(){return i.media?i.media.setMediaKeys(t):new Promise(function(e,r){i.mediaResolved=function(){if(i.mediaResolved=void 0,!i.media)return r(new Error("Attempted to set mediaKeys without media element attached"));i.mediaKeys=t,i.media.setMediaKeys(t).then(e).catch(r)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(function(){i.log('Media-keys set for "'.concat(e,'"')),r.push(n),i.setMediaKeysQueue=i.setMediaKeysQueue.filter(function(e){return-1===r.indexOf(e)})})}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,i,r){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,i,e);if(!o)throw new Error("Invalid response from configured generateRequest filter");t=o.initDataType,i=o.initData?o.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log('Skipping key-session request for "'.concat(r,'" (no initData)')),Promise.resolve(e);var l=yo(e.decryptdata),u=e.decryptdata.uri;this.log('Generating key-session request for "'.concat(r,'" keyId: ').concat(l," URI: ").concat(u," (init data type: ").concat(t," length: ").concat(i.byteLength,")"));var c=new Pn,d=e._onmessage=function(t){var i=e.mediaKeysSession;if(i){var r=t.messageType,n=t.message;a.log('"'.concat(r,'" message event for session "').concat(i.sessionId,'" message size: ').concat(n.byteLength)),"license-request"===r||"license-renewal"===r?a.renewLicense(e,n).catch(function(e){c.eventNames().length?c.emit("error",e):a.handleError(e)}):"license-release"===r?e.keySystem===hr.FAIRPLAY&&a.updateKeySession(e,lr("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(r,'"'))}else c.emit("error",new Error("invalid state"))},h=function(e,t){var i;t.keyStatus=e,e.startsWith("usable")?c.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=ko(e,t.decryptdata):"expired"===e?i=new Error("key expired (keyId: ".concat(l,")")):"released"===e?i=new Error("key released"):"status-pending"===e||a.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(l,")")),i&&(c.eventNames().length?c.emit("error",i):a.handleError(i))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){var i=a.getKeyStatuses(e);if(Object.keys(i).some(function(e){return"status-pending"!==i[e]})){if("expired"===i[l])return a.log("Expired key ".concat(Kt(i),' in key-session "').concat(e.mediaKeysSession.sessionId,'"')),void a.renewKeySession(e);var r=i[l];if(r)h(r,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(r="internal-error",e)}},1e3)),a.log("No status for keyId ".concat(l," (").concat(Kt(i),")."))}}}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,i).then(function(){a.log('Request generated for key-session "'.concat(e.mediaKeysSession.sessionId,'" keyId: ').concat(l," URI: ").concat(u))}).catch(function(t){throw new To({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,i={};return e.mediaKeysSession.keyStatuses.forEach(function(r,n){if("string"==typeof n&&"object"===S(r)){var a=n;n=r,r=a}var s="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===hr.PLAYREADY&&16===s.length){var o=be(s);i[o]=r,ur(s)}var l=be(s);"internal-error"===r&&(t.bannedKeyIds[l]=r),t.log('key status change "'.concat(r,'" for keyStatuses keyId: ').concat(l,' key-session "').concat(e.mediaKeysSession.sessionId,'"')),i[l]=r}),i}},{key:"fetchServerCertificate",value:function(e){var t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(n,a){var s={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,i,r){n(e.data)},onError:function(t,i,n,o){a(new To({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(r,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,i,n){a(new To({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(r,")")))},onAbort:function(e,t,i){a(new Error("aborted"))}};i.load(s,l,u)})):Promise.resolve()}},{key:"setMediaKeysServerCertificate",value:function(e,t,i){var r=this;return new Promise(function(n,a){e.setServerCertificate(i).then(function(a){r.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(i.byteLength,') on "').concat(t,'"')),n(e)}).catch(function(e){a(new To({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 i=this;return this.requestLicense(e,new Uint8Array(t)).then(function(t){return i.updateKeySession(e,new Uint8Array(t)).catch(function(t){throw new To({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 i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var r=(new DOMParser).parseFromString(i,"application/xml"),n=r.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=r.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return lr(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,i,r){var n=this,a=this.config.licenseXhrSetup;return a?Promise.resolve().then(function(){if(!i.decryptdata)throw new Error("Key removed");return a.call(n.hls,e,t,i,r)}).catch(function(s){if(!i.decryptdata)throw s;return e.open("POST",t,!0),a.call(n.hls,e,t,i,r)}).then(function(i){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}},{key:"requestLicense",value:function(e,t){var i=this,r=this.config.keyLoadPolicy.default;return new Promise(function(n,a){var s=i.getLicenseServerUrlOrThrow(e.keySystem);i.log("Sending license request to URL: ".concat(s));var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received ".concat(l instanceof ArrayBuffer?l.byteLength:l));var u=i.config.licenseResponseCallback;if(u)try{l=u.call(i.hls,o,s,e)}catch(e){i.error(e)}n(l)}else{var c=r.errorRetry,d=c?c.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>d||o.status>=400&&o.status<500)a(new To({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-i._requestLicenseFailureCount+1;i.warn("Retrying license request, ".concat(h," attempts left")),i.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,i.setupLicenseXHR(o,s,e,t).then(function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==hr.PLAYREADY&&(n=i.unpackPlayReadyKeyMessage(r,n)),r.send(n)}).catch(a)})}},{key:"onDestroying",value:function(){this.unregisterListeners(),this._clear()}},{key:"onMediaAttached",value:function(e,t){if(this.config.emeEnabled){var i=t.media;this.media=i,ln(i,"encrypted",this.onMediaEncrypted),ln(i,"waitingforkey",this.onWaitingForKey);var r=this.mediaResolved;r?r():this.mediaKeys=i.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,i=this;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};var r=this.mediaResolved;if(r&&r(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,br.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return i.removeSession(e)}).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch(function(e){i.log("Could not clear media keys: ".concat(e)),i.hls&&i.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){i.log("Could not close sessions and clear media keys: ".concat(e)),i.hls&&i.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&&i.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear()}},{key:"onManifestLoaded",value:function(e,t){var i=t.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(r.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(r)}}},{key:"removeSession",value:function(e){var t=this,i=e.mediaKeysSession,r=e.licenseXhr,n=e.decryptdata;if(i){this.log('Remove licenses and keys and close session "'.concat(i.sessionId,'" keyId: ').concat(be((null==n?void 0:n.keyId)||[]))),e._onmessage&&(i.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.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),i.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 i.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 be(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}po.CDMCleanupPromise=void 0;var To=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[i])).data=void 0,e.error||(e.error=new Error(i)),r.data=e,e.err=e.error,r}return d(t,e),o(t)}(L(Error));function ko(e,t){var i="output-restricted"===e,r=i?Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new To({type:J.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},i?"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 i=this.hls.config;if(i.capLevelOnFPSDrop){var r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,i){var r=performance.now();if(t){if(this.lastTime){var n=r-this.lastTime,a=i-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(ee.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:i}),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=r,this.lastDroppedFrames=i,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 Ao(e,t){var i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function bo(e,t){var i=e.mode;if("disabled"===i&&(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(i){Te.debug("[texttrack-utils]: ".concat(i));try{var r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){Te.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(e))}}"disabled"===i&&(e.mode=i)}function Lo(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===i&&(e.mode=i)}function Io(e,t,i,r){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,i){var r=[],n=function(e,t){if(t<=e[0].startTime)return 0;var i=e.length-1;if(t>e[i].endTime)return-1;var r,n=0,a=i;for(;n<=a;)if(t<e[r=Math.floor((a+n)/2)].startTime)a=r-1;else{if(!(t>e[r].startTime&&n<i))return r;n=r+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<=i)r.push(o);else if(o.startTime>i)return r}return r}(e.cues,t,i),s=0;s<a.length;s++)r&&!r(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}function Ro(e){for(var t=[],i=0;i<e.length;i++){var r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}var wo=function(e){function t(e){var i;return a(this,t),(i=n(this,t,[e,"subtitle-track-controller"])).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var e=null,t=Ro(i.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}var n=i.findTrackForTextTrack(e);i.subtitleTrack!==n&&i.setSubtitleTrack(n)}},i.registerListeners(),i}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 i=this.media;if(i){var r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!r)Ro(i.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 i=t.id,r=t.groupId,n=t.details,a=this.tracksInGroup[i];if(a&&a.groupId===r){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(i,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(r," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),i===this.trackId&&this.playlistLoaded(i,t,s)}else this.warn("Subtitle track with id:".concat(i," and group:").concat(r," 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 i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(function(e){return-1===(null==r?void 0:r.indexOf(e))})){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!i||-1!==i.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=Yt(s,a);if(o>-1)n=a[o];else{var l=Yt(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==i?void 0:i.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,i=this.selectDefaultTrack,r=0;r<t.length;r++){var n=t[r];if((!i||n.default)&&(i||e)&&(!e||zt(n,e)))return r}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,i=0;i<t.length;i++){if(us(t[i],e))return i}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 i=this.currentTrack;if(i&&zt(e,i))return i;var r=Yt(e,this.tracksInGroup);if(r>-1){var n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}if(i)return null;var a=Yt(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,i){E(t,"loadingPlaylist",this,3)([e,i]);var r=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,i),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(r,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.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:r,groupId:n,deliveryDirectives:i||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this.media;if(e){var t,i=Ro(e.textTracks),r=this.currentTrack;if(r&&((t=i.filter(function(e){return us(r,e)})[0])||this.warn('Unable to find subtitle TextTrack with name "'.concat(r.name,'" and language "').concat(r.lang,'"'))),[].slice.call(i).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 i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),r){var n=!!r.details&&!r.details.live;if(e!==this.trackId||r!==i||!n){this.log("Switching to subtitle-track ".concat(e)+(r?' "'.concat(r.name,'" lang:').concat(r.lang," group:").concat(r.groupId):""));var a=r.id,s=r.groupId,o=void 0===s?"":s,l=r.name,u=r.type,c=r.url;this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:c});var d=this.switchParams(r.url,null==i?void 0:i.details,r.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,i=e.length;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}var Do=.025,Co=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function _o(e,t,i){return"".concat(e.identifier,"-").concat(i+1,"-").concat(Po(t))}var xo=function(){return o(function e(t,i){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=i,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 i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)}},{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)<Do))},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"]?Co.Range:Co.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))<Do)?t.start:t.start+t.duration}function Oo(e,t,i){var r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function Fo(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function No(e){var t=e.timelineStart,i=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+i).toFixed(2),"]")}var Bo=function(){return o(function e(t,i,r,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(i);this.interstitial=r,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 i=t.media;s.removeMediaListeners(),s.mediaAttached=i,s.interstitial.playoutLimit&&(i.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 i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=ji.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=i-.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=ji.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 i=t-this.startOffset;if(i>0&&i<e)return i}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 i=e-t;if(Math.abs(i)>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,i=this.duration;return Math.min(Math.max(0,e-t),i)}},{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,i){var r;null==(r=this.hls)||r.on(e,t)}},{key:"once",value:function(e,t,i){var r;null==(r=this.hls)||r.once(e,t)}},{key:"off",value:function(e,t,i){var r;null==(r=this.hls)||r.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":"")}}])}(),Uo=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,["interstitials-sched",i])).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=e,r}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(i,r){return e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i},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 i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(n=r[i])&&n.event;){var n;i--}return i}},{key:"findItemIndexAtTime",value:function(e,t){var i=this.items;if(i)for(var r=0;r<i.length;r++){var n=i[r];if(t&&"primary"!==t&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var i=this.items;if(i)for(var r=e;r<=t&&i[r];r++){var n=i[r].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var i=t.length;i--;){var r;if((null==(r=t[i].event)?void 0:r.identifier)===e)return i}return-1}},{key:"findAssetIndex",value:function(e,t){var i=e.assetList,r=i.length;if(r>1)for(var n=0;n<r;n++){var a=i[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===r-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 i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var i=this,r=e.main.details,n=r.dateRanges,a=this.events,s=this.parseDateRanges(n,{url:r.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 i=e.cue.pre,r=e.cue.post,n=t.cue.pre,a=t.cue.post;if(i&&!n)return-1;if(n&&!i)return 1;if(r&&!a)return 1;if(a&&!r)return-1;if(!(i||n||r||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){i.removeEvent(e)}),this.updateSchedule(e,l)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this.events||[];if(r.length||t.length||this.length<2){var n=this.items,a=this.parseSchedule(r,e);(i||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,i){for(var r=[],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 xo(o,t),this.eventMap[s]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r}},{key:"parseSchedule",value:function(e,t){var i=[],r=t.main.details,n=r.live?1/0:r.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,r){var l=t.cue.pre,u=t.cue.post,c=e[r-1]||null,d=t.appendInPlace,h=u?n:t.startOffset,f=t.duration,v=t.timelineOccupancy===Co.Range?f:0,g=t.resumptionOffset,m=(null==c?void 0:c.startTime)===h,p=h+t.cumulativeDuration,y=d?p+f:h+g;if(l||!u&&h<=0){var E=o;o+=v,t.timelineStart=p;var T=a;a+=f,i.push({event:t,start:p,end:y,playout:{start:T,end:a},integrated:{start:E,end:o}})}else{if(!(h<=n))return;if(!m){var k=h-s;if(k>.033){var S=s,A=o;o+=k;var b=a;a+=k;var L={previousEvent:e[r-1]||null,nextEvent:t,start:S,end:S+k,playout:{start:b,end:a},integrated:{start:A,end:o}};i.push(L)}else k>0&&c&&(c.cumulativeDuration+=k,i[i.length-1].end=h)}u&&(y=p),t.timelineStart=p;var I=o;o+=v;var R=a;a+=f,i.push({event:t,start:p,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,i.push({previousEvent:(null==(l=i[i.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{i.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 i}},{key:"setDurations",value:function(e,t,i){this.durations={primary:e,playout:t,integrated:i}}},{key:"resolveOffsets",value:function(e,t){var i=this,r=t.main.details,n=r.live?1/0:r.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;(i.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=ei(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(i.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&&i.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 i=this,r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>Do?(this.log('"'.concat(e.identifier,'" resumption ').concat(r," not aligned with estimated timeline end ").concat(n)),!1):!Object.keys(t).some(function(n){var a=t[n].details,s=a.edge;if(r>=s)return i.log('"'.concat(e.identifier,'" resumption ').concat(r," past ").concat(n," playlist end ").concat(s)),!1;var o=ei(null,a.fragments,r);if(!o)return i.log('"'.concat(e.identifier,'" resumption ').concat(r," 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-r)<Do+l||Math.abs(o.end-r)<Do+l)&&(i.log('"'.concat(e.identifier,'" resumption ').concat(r," 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,i=0,r=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+i;s.startOffset=i,s.timelineStart=o,r||(r=null===s.duration),n||(n=!!s.error),i+=s.error?0:s.duration||0}e.duration=r&&!n?Math.max(i,e.duration):i}}},{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 Vo=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 i,r=this,n=e.assetListUrl;try{i=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:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={responseType:"json",url:i.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,i,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,r.hls.trigger(ee.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=r.assignAssetListError(e,Z.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,i,a);r.hls.trigger(ee.ERROR,l)}},onError:function(t,i,n,a){var s=r.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(i.url,")")),i.url,a,n);r.hls.trigger(ee.ERROR,s)},onTimeout:function(t,i,n){var a=r.assignAssetListError(e,Z.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(i.url,")")),i.url,t,n);r.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,i,r,n,a){return e.error=i,{type:J.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:a,stats:n}}}])}();function Ho(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,i){var r;return a(this,t),(r=n(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&r.schedule){var t=e-r.timelinePos;if(!(Math.abs(t)<1/7056e5)){var i=t<=-.01;r.timelinePos=e,r.bufferedPos=e;var n=r.playingItem;if(n){if(i)r.schedule.resetErrorsInRange(e,e-t)&&r.updateSchedule(!0);if(r.checkBuffer(),i&&e<n.start||e>=n.end){var a,s=r.findItemIndex(n),o=r.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(i?-1:1),r.log("seeked ".concat(i?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!r.isInterstitial(n)&&null!=(a=r.media)&&a.paused&&(r.shouldPlay=!1),!i&&o>s){var l=r.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void r.setSchedulePosition(l)}r.setSchedulePosition(o)}else{var u=r.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(i&&e<d||e>=d+h)null!=(c=n.event)&&c.appendInPlace&&(r.clearAssetPlayers(n.event,n),r.flushFrontBuffer(e)),r.setScheduleToAssetAtTime(e,u)}else if(r.playingLastItem&&r.isInterstitial(n)){var f=n.event.assetList[0];f&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(e,f))}}}else r.checkBuffer()}}},r.onTimeupdate=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&e>r.timelinePos){r.timelinePos=e,e>r.bufferedPos&&r.checkBuffer();var t=r.playingItem;if(t&&!r.playingLastItem){if(e>=t.end){r.timelinePos=t.end;var i=r.findItemIndex(t);r.setSchedulePosition(i+1)}var n=r.playingAsset;if(n)e>=n.timelineStart+(n.duration||0)&&r.setScheduleToAssetAtTime(e,n)}}},r.onScheduleUpdate=function(e,t){var i=r.schedule;if(i){var n=r.playingItem,a=i.events||[],s=i.items||[],o=i.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&r.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return Go(e)})," pos: ").concat(r.timelinePos)),l.length&&r.log("Removed events ".concat(l));var c=null,d=null;n&&(c=r.updateItem(n,r.timelinePos),r.itemsMatch(n,c)?r.playingItem=c:r.waitingItem=r.endedItem=null),r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var h=r.bufferingItem;if(h&&(d=r.updateItem(h,r.bufferedPos),r.itemsMatch(h,d)?r.bufferingItem=d:h.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){r.clearAssetPlayer(e.identifier,null)})}),r.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(n){Math.abs(i)>Do&&r.warn("".concat(n,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(r.hls.trigger(ee.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),r.isInterstitial(n)&&l.includes(n.event.identifier))return r.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),void r.primaryFallback(n.event);n&&r.trimInPlace(c,n),h&&d!==c&&r.trimInPlace(d,h),r.checkBuffer()}}},r.hls=e,r.HlsPlayerClass=i,r.assetListLoader=new Vo(e),r.schedule=new Uo(r.onScheduleUpdate,e.logger),r.registerListeners(),r}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 i=this.media=t.media;ln(i,"seeking",this.onSeeking),ln(i,"timeupdate",this.onTimeupdate),ln(i,"play",this.onPlay),ln(i,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var n=this.findItemIndex(i);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 i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),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},i=function(t){return t?e.getAssetPlayer(t.identifier):t},r=function(t,r,a,s,o){if(t){var l=t[r].start,u=t.event;if(u){if("playout"===r||u.timelineOccupancy!==Co.Point){var c=i(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 i,r;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.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=i(e.playingAsset),m=(null==g?void 0:g.media)||e.primaryMedia;if(m){var p="primary"===n?m.currentTime:r(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-p,E=(f?p:m.currentTime)+y;if(E>=0&&(!g||f||E<=g.duration))return void(m.currentTime=E)}}if(c){var T=t;if("primary"!==n){var k=t-c[n].start;T=c.start+k}var S=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!S&&!c.event.appendInPlace){if(l){var A=e.findItemIndex(l);if(u>A){var b=e.schedule.findJumpRestrictedIndex(A+1,u);if(b>A)return void e.setSchedulePosition(b)}var L=0;if(S)e.timelinePos=T,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 D=e.media||(f?null==d?void 0:d.media:null);D&&(D.currentTime=T)}}}},o=function(){var i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;var r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){var i,n=t(),a=e.bufferingItem;return a&&a===n&&(r(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(i=e.bufferingAsset)?void 0:i.startOffset))||0},get currentTime(){var t=o(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){var i=o(),r=e.effectivePlayingItem;r&&r===i&&s(t+r.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,i=null==(t=o())?void 0:t.event.assetList;return i?i.map(function(t){return e.getAssetPlayer(t.identifier)}):[]},get playingIndex(){var t,i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.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 i=t();return e.findItemIndex(i)},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 r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(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,i){var r;if(0!==t&&"primary"!==i&&null!=(r=e.schedule)&&r.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[i].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){var r=e.findItemIndex(t);if(i.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(i,r,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,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var i=this.waitingItem||this.playingItem;if(!this.isInterstitial(i)||i.event.appendInPlace){var r=this.media;!r&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);var n=null==(t=r)?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 i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});var n=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(Kt(n))),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}},{key:"transferMediaTo",value:function(e,t){var i,r,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(i=this.detachedData)?void 0:i.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==(r=s.mediaSource)?void 0:r.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 m=l&&e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:!l||m,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 i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){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(r&&!this.playingItem){var l=e.findItemIndex(r);this.setSchedulePosition(l)}}}},{key:"advanceAssetBuffering",value:function(e,t){var i=e.event,r=i.findAssetIndex(t),n=Fo(i,r);if(i.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,i){var r=Fo(e,i);if(e.isAssetPastPlayoutLimit(r)){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[r];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(t,r)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var i=this.schedule;if(i){var r=t.parentIdentifier,n=i.getEvent(r);if(n){var a=i.findEventIndex(r),s=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;if(r&&!this.playbackDisabled){var n=e>=0?r[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:r.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:r.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,r,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,i,r,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 i=t.interstitial,r=s.findEventIndex(i.identifier);(r<e||r>e+1)&&a.clearInterstitial(i,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===i){var d=Fo(c,(i=s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,i);i=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,i);if(this.eventItemsMatch(o,h||r)||(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[i];if(!v)return void this.advanceAfterAssetEnded(c,e,i||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(i+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,i)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,i,t,e,l),this.shouldPlay&&Ho(f.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Ho(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.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,i){var r,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==(r=this.detachedData)||!r.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(i){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 i=e.start;if(this.primaryLive){var r=this.primaryDetails;if(0===t)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:ji.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Ko("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.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 i=this.hls.levels[t.level];if(i.details){var r=fe(fe({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(r){var n=fe(fe({},r),{},{audio:i});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{audio:i})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(r){var n=fe(fe({},r),{},{subtitles:i});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{subtitles:i})}},{key:"onAudioTrackSwitching",value:function(e,t){var i=qt(t);this.playerQueue.forEach(function(e){var r=e.hls;return r&&(r.setAudioOption(t)||r.setAudioOption(i))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var i=qt(t);this.playerQueue.forEach(function(e){var r=e.hls;return r&&(r.setSubtitleOption(t)||-1!==t.id&&r.setSubtitleOption(i))})}},{key:"onBufferCodecs",value:function(e,t){var i=t.tracks;i&&(this.requiredTracks=i)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var i=0;i<t.length;i++){var r=t[i];if(r.cue.post){var n,a=this.schedule.findEventIndex(r.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 i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;return e&&r&&r[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var i=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,r){e.event.isAssetPastPlayoutLimit(r)&&i.clearAssetPlayer(t.identifier,null)});var r=e.end+.25,n=ji.bufferInfo(this.primaryMedia,r,0);if(n.end>r||(n.nextStart||0)>r){this.log("trim buffered interstitial ".concat(Go(e)," (was ").concat(Go(t),")"));this.attachPrimary(r,null,!0),this.flushFrontBuffer(r)}}}},{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 i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.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],i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}},{key:"checkBuffer",value:function(e){var t,i=null==(t=this.schedule)?void 0:t.items;if(i){var r=ji.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}}},{key:"updateBufferedPos",value:function(e,t,i){var r=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&r)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=r.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 i&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var i=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var r=i.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,i=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,i)&&r){var n=r.items,a=r.events;if(!n||!a)return i;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:i?i.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(Go(e))+(i?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,i){var r=t.getAssetPlayer(e.identifier);r&&(i===u&&r.loadSource(),r.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 i}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;if(r)if(r.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),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}},{key:"bufferedToEvent",value:function(e,t){var i=e.event,r=0===i.assetList.length&&!i.assetListLoader,n=i.cue.once;if(r||!n){var a=this.preloadAssets(i,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var i=e.assetUrl,r=e.assetList.length,n=0===r&&!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(i?1:r," ").concat(e).concat(s?" live-start: ".concat(c," start-offset: ").concat(s):"")),i)return this.createAsset(e,0,0,o,e.duration,i);var h=this.assetListLoader.loadAssetList(e,s);h&&(e.assetListLoader=h)}else if(!a&&r){for(var f=t;f<r;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 m=e.assetList[t];if(m){var p=this.getAssetPlayer(m.identifier);return p&&p.loadSource(),p}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at ".concat(e)),Object.keys(i).forEach(function(i){t.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})}))}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,i=0;i<t.length;i++)if(e===t[i].assetId)return i;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 i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null}},{key:"createAsset",value:function(e,t,i,r,n,a){var s={parentIdentifier:e.identifier,identifier:_o(e,a,t),duration:n,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,i){var r=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 m=new Bo(this.HlsPlayerClass,v,e,t);this.playerQueue.push(m),e.assetList[i]=t;var p=!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=r.schedule)?void 0:a.findEventIndex(e.identifier))||-1;r.handleAssetItemError(o,e,l,i,s.message)}else{var u=n.edge-n.fragmentStart,c=t.duration;(p||null===c||u>c)&&(p=!1,r.log('Interstitial asset "'.concat(f,'" duration change ').concat(c," > ").concat(u)),t.duration=u,r.updateSchedule())}};m.on(ee.LEVEL_UPDATED,function(e,t){var i=t.details;return y(i)}),m.on(ee.LEVEL_PTS_UPDATED,function(e,t){var i=t.details;return y(i)}),m.on(ee.EVENT_CUE_ENTER,function(){return r.onInterstitialCueEnter()});var E=function(e,t){var i=r.getAssetPlayer(f);if(i&&t.tracks){i.off(ee.BUFFER_CODECS,E),i.tracks=t.tracks;var n=r.primaryMedia;r.bufferingAsset===i.assetItem&&n&&!i.media&&r.bufferAssetPlayer(i,n)}};m.on(ee.BUFFER_CODECS,E);m.on(ee.BUFFERED_TO_END,function(){var i,n=r.getAssetPlayer(f);if(r.log("buffered to end of asset ".concat(n)),n&&r.schedule){var a=r.schedule.findEventIndex(e.identifier),s=null==(i=r.schedule.items)?void 0:i[a];r.isInterstitial(s)&&r.advanceAssetBuffering(s,t)}});var T=function(t){return function(){if(r.getAssetPlayer(f)&&r.schedule){r.shouldPlay=!0;var i=r.schedule.findEventIndex(e.identifier);r.advanceAfterAssetEnded(e,i,t)}}};return m.once(ee.MEDIA_ENDED,T(i)),m.once(ee.PLAYOUT_LIMIT_REACHED,T(1/0)),m.on(ee.ERROR,function(t,n){if(r.schedule){var a=r.getAssetPlayer(f);if(n.details===Z.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void r.handleInPlaceStall(e):(r.onTimeupdate(),void r.checkBuffer(!0));r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,"Asset player error ".concat(n.error," ").concat(e))}}),m.on(ee.DESTROYING,function(){if(r.getAssetPlayer(f)&&r.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};r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(No(t))),this.hls.trigger(ee.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:m}),m}},{key:"clearInterstitial",value:function(e,t){this.clearAssetPlayers(e,t),e.reset()}},{key:"clearAssetPlayers",value:function(e,t){var i=this;e.assetList.forEach(function(e){i.clearAssetPlayer(e.identifier,t)})}},{key:"resetAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'.concat(e,'" after error'));var i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var i=this.getAssetPlayerQueueIndex(e);if(-1!==i){var r=this.playerQueue[i];this.log("clear ".concat(r," toSegment: ").concat(t?Go(t):t)),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,i,r,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,i[r]),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:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}},{key:"bufferAssetPlayer",value:function(e,t){var i,r;if(this.schedule){var n=e.interstitial,a=e.assetItem,s=this.schedule.findEventIndex(n.identifier),o=null==(i=this.schedule.items)?void 0:i[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==(r=this.detachedData)?void 0:r.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,i=this.primaryMedia;if(t&&i){var r=i.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||r-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(r,")")),o&&(l/i.playbackRate<.5||s.bufferedInPlaceToEnd(i))&&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,i,r,n){if(e.details!==Z.BUFFER_STALLED_ERROR){var a=t.assetList[r]||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:ki(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:i,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=r;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,i,r):h&&h.identifier===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,i=this.effectivePlayingItem,r=this.timelinePos;if(i){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(r," playing: ").concat(Go(i)," error: ").concat(e.error)),-1===r&&(r=this.hls.startPosition);var n=this.updateItem(i,r);this.itemsMatch(i,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===r)return void this.checkStart();if(this.schedule){var a=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(a)}}},{key:"onAssetListLoaded",value:function(e,t){var i,r,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(i=this.schedule)&&i.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var i=parseFloat(e.DURATION);n.createAsset(a,t,c,l+c,i,e.URI),c+=i}),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==(r=this.bufferingItem)?void 0:r.event;if(h){var v,g=this.schedule.findEventIndex(s),m=null==(v=this.schedule.items)?void 0:v[g];if(m){if(!this.playingItem&&this.timelinePos>m.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return a.error=new Error("Interstitial ".concat(o.length?"no longer within playback range":"asset-list is empty"," ").concat(this.timelinePos," ").concat(a)),this.log(a.error.message),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(m)}this.setSchedulePosition(g)}else if((null==f?void 0:f.identifier)===s){var p=a.assetList[0];if(p){var y=this.getAssetPlayer(p.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 i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break;case Z.BUFFER_STALLED_ERROR:var r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace)return void this.handleInPlaceStall(r.event);this.log("Primary player stall @".concat(this.timelinePos," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(ve),Wo=function(e){function t(e,i,r){var s;return a(this,t),(s=n(this,t,[e,i,r,"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,i){this.tracksBuffered=[],E(t,"onMediaDetaching",this,3)([e,i])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var i=t.frag,r=t.success;if(this.fragContextChanged(i)||(Oe(i)&&(this.fragPrevious=i),this.state=hn),r){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=i.start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=i.start+i.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}}},{key:"onBufferFlushing",value:function(e,t){var i=t.startOffset,r=t.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var n=r-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(i,n,oe)}}},{key:"onError",value:function(e,t){var i=t.frag;(null==i?void 0:i.type)===oe&&(t.details===Z.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dn&&(this.state=hn))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var i=this,r=t.subtitleTracks;this.levels&&os(this.levels,r)?this.levels=r.map(function(e){return new Gt(e)}):(this.tracksBuffered=[],this.levels=r.map(function(e){var t=new Gt(e);return i.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 i;if(this.currentTrackId=t.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==dn&&this.setInterval(500)}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var i,r=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!=(i=o.details)&&i.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&&zr(a,l=d.start);else a.hasProgramDateTime&&u.hasProgramDateTime?(on(a,u),l=a.fragmentStart):d&&zr(a,l=d.start);u&&!this.startFragRequested&&this.setStartPosition(u,l)}if(o.details=a,this.levelLastLoaded=o,s===r)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)ei(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,i=e.frag,r=e.payload,n=i.decryptdata,a=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=n&&n.key&&n.iv&&ar(n.method)){var s=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,sr(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:i}),e}).then(function(e){var t=performance.now();a.trigger(ee.FRAG_DECRYPTED,{frag:i,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,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,n=this.getLoadPosition(),a=ji.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),s=a.end,o=a.len,l=i.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=r.maxFragLookUpTolerance,g=s>d-v?0:v;!(h=ei(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,i.details)))return;var m=u[h.sn-l.startSN-1];if(m&&m.cc===h.cc&&this.fragmentTracker.getState(m)===Si&&(h=m),this.fragmentTracker.getState(h)===Si){var p=this.mapToInitFragWhenRequired(h);p&&this.loadFragment(p,i,s)}}}else this.state=hn}},{key:"loadFragment",value:function(e,i,r){Oe(e)?E(t,"loadFragment",this,3)([e,i,r]):this._loadInitSegment(e,i)}},{key:"mediaBufferTimeRanges",get:function(){return new qo(this.tracksBuffered[this.currentTrackId]||[])}}])}(An),qo=o(function e(t){a(this,e),this.buffered=void 0;var i=function(e,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(i,") is greater than the maximum bound (").concat(r,")"));return t[i][e]};this.buffered={get length(){return t.length},end:function(e){return i("end",e,t.length)},start:function(e){return i("start",e,t.length)}}}),Yo={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(Yo[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"],il=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 i="function"==typeof t?t():t;Te.log("".concat(this.time," [").concat(e,"] ").concat(i))}}}])}(),rl=function(e){for(var t=[],i=0;i<e.length;i++)t.push(e[i].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"],i=0;i<t.length;i++){var r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}},{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 i=0;i<Qo;i++)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 i=this.pos+1;i<t+1;i++)this.chars[i].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 i=zo(e);this.pos>=Qo?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+i+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(i,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,i=0;i<Qo;i++){var r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}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 i=0;i<Xo;i++)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,i=0;i<Xo;i++)if(!this.rows[i].equals(e.rows[i])){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 i=0;i<Xo;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[r].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[r+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,i=this.rows.splice(t,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),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=[],i="",r=-1,n=0;n<Xo;n++){var a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),ll=function(){return o(function e(t,i,r){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=i,this.mode=null,this.verbose=0,this.displayedMemory=new ol(r),this.nonDisplayedMemory=new ol(r),this.lastOutputScreen=new ol(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r},[{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,i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return r+": "+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 i=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}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,i,r){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 il;this.channels=[null,new ll(t,i,n),new ll(t+1,r,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 i=this;this.logger.time=e;for(var r=function(e){var r=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===r&&0===n)return 0;i.logger.log(3,function(){return"["+rl([t[e],t[e+1]])+"] -> ("+rl([r,n])+")"});var o=i.cmdHistory;if(r>=16&&r<=31){if(function(e,t,i){return i.a===e&&i.b===t}(r,n,o))return cl(null,null,o),i.logger.log(3,function(){return"Repeated command ("+rl([r,n])+") is dropped"}),0;cl(r,n,i.cmdHistory),(a=i.parseCmd(r,n))||(a=i.parseMidrow(r,n)),a||(a=i.parsePAC(r,n)),a||(a=i.parseBackgroundAttributes(r,n))}else cl(null,null,o);if(!a&&(s=i.parseChars(r,n))){var l=i.currentChannel;if(l&&l>0)i.channels[l].insertChars(s);else i.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||i.logger.log(2,function(){return"Couldn't parse cleaned data "+rl([r,n])+" orig: "+rl([t[e],t[e+1]])})},n=0;n<t.length;n+=2)r(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 i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}},{key:"parseMidrow",value:function(e,t){var i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+rl([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var r=e<=23?1:2;i=t>=64&&t<=95?1===r?$o[e]:Zo[e]:1===r?Jo[e]:el[e];var n=this.channels[r];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)}},{key:"interpretPAC",value:function(e,t){var i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}},{key:"parseChars",value:function(e,t){var i,r,n=null,a=null;(e>=25?(i=2,a=e-8):(i=1,a=e),a>=17&&a<=19)?(r=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+zo(r)+"' in channel "+i}),n=[r]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,function(){return"Char codes = "+rl(n).join(",")}),n}},{key:"parseBackgroundAttributes",value:function(e,t){var i;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=tl[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(r),!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 i=this.channels[t];i&&i.cueSplitAtTime(e)}}}])}();function cl(e,t,i){i.a=e,i.b=t}var dl=function(){if(null!=dr&&dr.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function n(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];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="",m=!0,p="auto",y="start",E=50,T="middle",k=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 r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return p},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=r(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 T},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return k},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");k=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(e){var t=r(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,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}var i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[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,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,i){for(var r=0;r<i.length;++r)if(t===i[r]){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 i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}])}();function gl(e,t,i,r){var n=r?e.split(r):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(i);if(2===s.length)t(s[0],s[1])}}var ml=new dl(0,0,""),pl="middle"===ml.align?"middle":"center";function yl(e,t,i){var r=e;function n(){var t=fl(e);if(null===t)throw new Error("Malformed timestamp: "+r);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'): "+r);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var r=new vl;gl(e,function(e,t){var n;switch(e){case"region":for(var a=i.length-1;a>=0;a--)if(i[a].id===t){r.set(e,i[a].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),r.integer(e,n[0]),r.percent(e,n[0])&&r.set("snapToLines",!1),r.alt(e,n[0],["auto"]),2===n.length&&r.alt("lineAlign",n[1],["start",pl,"end"]);break;case"position":n=t.split(","),r.percent(e,n[0]),2===n.length&&r.alt("positionAlign",n[1],["start",pl,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",pl,"end","left","right"])}},/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");var n=r.get("line","auto");"auto"===n&&-1===ml.line&&(n=-1),t.line=n,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",pl);var a=r.get("position","auto");"auto"===a&&50===ml.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 Tl=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 i(){var e=t.buffer,i=0;for(e=El(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;var r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}function r(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=i()).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=i(),t.state){case"HEADER":/:/.test(n)?r(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}}])}(),kl=/\r\n|\n\r|\n|\r/g,Sl=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return e.slice(i,i+t.length)===t};function Al(e,t,i){return Po(e.toString())+Po(t.toString())+Po(i)}function bl(e,t,i,r,n,a,s){var o,l=new Tl,u=Ae(new Uint8Array(e)).trim().replace(kl,"\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=i[r],s=i.ccOffset,l=(f-d)/9e4;if(null!=a&&a.new&&(void 0!==v?s=i.ccOffset=a.start:function(e,t,i){var r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(a=n)&&a.new;){var a;e.ccOffset+=r.start-n.start,r.new=!1,n=e[(r=n).prevCC]}e.presentationOffset=i}(i,r,l)),l){if(!t)return void(o=new Error("Missing initPTS for VTT MPEGTS"));s=l-i.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=Al(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)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(X(t)&&X(i)&&X(r)&&X(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*i,t+=6e4*r,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,i,r){var n=Ye(new Uint8Array(e),["mdat"]);if(0!==n.length){var a=n.map(function(e){return Ae(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 i(function(e,t){var i=(new DOMParser).parseFromString(e,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)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]=r.getAttribute("ttp:".concat(t))||n[t],e},{}),s="preserve"!==r.getAttribute("xml:space"),o=Cl(Dl(r,"styling","style")),l=Cl(Dl(r,"layout","region")),u=Dl(r,"body","[begin]");return[].map.call(u,function(e){var i=_l(e,s);if(!i||!e.hasAttribute("begin"))return null;var r=Ol(e.getAttribute("begin"),a),n=Ol(e.getAttribute("dur"),a),u=Ol(e.getAttribute("end"),a);if(null===r)throw Ml(e);if(null===u){if(null===n)throw Ml(e);u=r+n}var c=new dl(r-t,u-t,i);c.id=Al(c.startTime,c.endTime,c.text);var d=function(e,t,i){var r="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&&i.hasOwnProperty(s)&&(n=i[s]);return a.reduce(function(i,a){var s=xl(t,r,a)||xl(e,r,a)||xl(n,r,a);return s&&(i[a]=s),i},{})}(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){r(e)}}else r(new Error("Could not parse IMSC1 mdat"))}function Dl(e,t,i){var r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Cl(e){return e.reduce(function(e,t){var i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function _l(e,t){return[].slice.call(e.childNodes).reduce(function(e,i,r){var n;return"br"===i.nodeName&&r?e+"\n":null!=(n=i.childNodes)&&n.length?_l(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function xl(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Ml(e){return new Error("Could not parse ttml timestamp ".concat(e))}function Ol(e,t){if(!e)return null;var i=fl(e);return null===i&&(Il.test(e)?i=function(e,t){var i=Il.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):Rl.test(e)&&(i=function(e,t){var i=Rl.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}var Fl=function(){return o(function e(t,i){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=i},[{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,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,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"),i=new Fl(this,"textTrack3"),r=new Fl(this,"textTrack4");this.cea608Parser1=new ul(1,e,t),this.cea608Parser2=new ul(3,i,r)}},{key:"addCues",value:function(e,t,i,r,n){for(var a=!1,s=n.length;s--;){var o=n[s],l=Gl(o[0],o[1],t,i);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],i),a=!0,l/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){var u=this.captionsTracks[e];this.Cues.newCue(u,t,i,r)}else{var c=this.Cues.newCue(null,t,i,r);this.hls.trigger(ee.CUES_PARSED,{type:"captions",cues:c,track:e})}}},{key:"onInitPtsFound",value:function(e,t){var i=this,r=t.frag,n=t.id,a=t.initPTS,s=t.timescale,o=t.trackId,l=this.unparsedVttFrags;n===ae&&(this.initPTS[r.cc]={baseTime:a,timescale:s,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach(function(e){i.initPTS[e.frag.cc]?i.onFragLoaded(ee.FRAG_LOADED,e):i.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 i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var n=i.textTracks[r];if(Ul(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,i=this.captionsTracks,r=this.media,n=t[e],a=n.label,s=n.languageCode,o=this.getExistingTrack(a,s);if(o)i[e]=o,Lo(i[e]),Ao(i[e],r);else{var l=this.createTextTrack("captions",a,s);l&&(l[e]=!0,i[e]=l)}}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}}},{key:"createTextTrack",value:function(e,t,i){var r=this.media;if(r)return r.addTextTrack(e,t,i)}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}},{key:"onMediaDetaching",value:function(e,t){var i=!!t.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach(function(e){Lo(r[e]),delete r[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 i=0;i<t.length;i++)Lo(t[i])}}},{key:"onSubtitleTracksUpdated",value:function(e,t){var i=this,r=t.subtitleTracks||[],n=r.some(function(e){return e.textCodec===Ll});if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(os(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var a=this.media,s=a?Ro(a.textTracks):null;if(this.tracks.forEach(function(e,t){var r;if(s){for(var n=null,a=0;a<s.length;a++)if(s[a]&&Ul(s[a],e)){n=s[a],s[a]=null;break}n&&(r=n)}if(r)Lo(r);else{var o=Bl(e);(r=i.createTextTrack(o,e.name,e.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)}),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 i=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var r="textTrack".concat(t[1]),n=i.captionsProperties[r];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 i,r,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(i=null==(r=t.part)?void 0:r.index)?i:-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 i=t.frag,r=t.payload;if(i.type===oe)if(r.byteLength){var n=i.decryptdata,a="stats"in t;if(null==n||!n.encrypted||a){var s=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),s&&s.textCodec===Ll?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}},{key:"_parseIMSC1",value:function(e,t){var i=this,r=this.hls;Pl(t,this.initPTS[e.cc],function(t){i._appendCues(t,e.level),r.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},function(t){r.logger.log("Failed to parse IMSC1: ".concat(t)),r.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}},{key:"_parseVTTs",value:function(e){var t,i=this,r=e.frag,n=e.payload,a=this.initPTS,s=this.unparsedVttFrags,o=a.length-1;if(a[r.cc]||-1!==o){var l=this.hls;bl(null!=(t=r.initSegment)&&t.data?rt(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,function(e){i._appendCues(e,r.level),l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},function(t){var a="Missing initPTS for VTT MPEGTS"===t.message;a?s.push(e):i._fallbackToIMSC1(r,n),l.logger.log("Failed to parse VTT cue: ".concat(t)),a&&o>r.cc||l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})})}else s.push(e)}},{key:"_fallbackToIMSC1",value:function(e,t){var i=this,r=this.tracks[e.level];r.textCodec||Pl(t,this.initPTS[e.cc],function(){r.textCodec=Ll,i._parseIMSC1(e,t)},function(){r.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach(function(e){return bo(r,e)})}else{var n=this.tracks[t];if(!n)return;var a=n.default?"default":"subtitles"+t;i.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 i=t.frag,r=t.samples;if(i.type!==ae||"NONE"!==this.closedCaptionsForLevel(i))for(var n=0;n<r.length;n++){var a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,s[0]),this.cea608Parser2.addData(r[n].pts,s[1])}}}}},{key:"onBufferFlushing",value:function(e,t){var i=t.startOffset,r=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<r)){if(!a||"video"===a){var o=this.captionsTracks;Object.keys(o).forEach(function(e){return Io(o[e],i,r)})}if(this.config.renderTextTracksNatively&&0===i&&void 0!==n){var l=this.textTracks;Object.keys(l).forEach(function(e){return Io(l[e],i,n)})}}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],i=31&e[0],r=2,n=0;n<i;n++){var a=e[r++],s=127&e[r++],o=127&e[r++];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 Bl(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Ul(e,t){return!!e&&e.kind===Bl(t)&&us(t,e)}function Gl(e,t,i,r){return Math.min(t,r)-Math.max(e,i)}var Vl=/\s/,Hl={newCue:function(e,t,i,r){for(var n,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<r.rows.length;d++)if(s=!0,o=0,l="",!(n=r.rows[d]).isEmpty()){for(var h,f=0;f<n.chars.length;f++)Vl.test(n.chars[f].uchar)&&s?o++:(l+=n.chars[f].uchar,s=!1);n.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;var v=El(l.trim()),g=Al(t,i,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,i,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 bo(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||Wl,this.controller=new self.AbortController,this.stats=new De},[{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,i){var r=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 i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(de({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(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=i,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&X(u)?u:c,this.requestTimeout=self.setTimeout(function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))},t.timeout),(es(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(i){var a;r.response=r.loader=i;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(r.requestTimeout),t.timeout=c,r.requestTimeout=self.setTimeout(function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))},c-(o-n.loading.start)),!i.ok){var l=i.status,u=i.statusText;throw new ql(u||"fetch, bad network response",l,i)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var i=function(e){var t=Kl.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(X(i))return i}var r=e.get("Content-Length");if(r)return parseInt(r)}(i.headers)||n.total;var d=null==(a=r.callbacks)?void 0:a.onProgress;return d&&X(t.highWaterMark)?r.loadProgressively(i,n,e,t.highWaterMark,d):s?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(function(i){var a,s,l=r.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=i[o];u&&(n.loaded=n.total=u);var c={url:l.url,data:i,code:l.status},d=null==(a=r.callbacks)?void 0:a.onProgress;d&&!X(t.highWaterMark)&&d(n,e,i,l),null==(s=r.callbacks)||s.onSuccess(c,n,e,l)}).catch(function(t){var i;if(self.clearTimeout(r.requestTimeout),!n.aborted){var a=t&&t.code||0,s=t?t.message:null;null==(i=r.callbacks)||i.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,i){var r=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,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<r||a.dataLength?(a.push(l),a.dataLength>=r&&n(t,i,a.flush().buffer,e)):n(t,i,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}();function Wl(e,t){return new self.Request(e.url,t)}var ql=function(e){function t(e,i,r){var s;return a(this,t),(s=n(this,t,[e])).code=void 0,s.details=void 0,s.code=i,s.details=r,s}return d(t,e),o(t)}(L(Error)),Yl=/^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 De,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,i){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=i,this.loadInternal()}},{key:"loadInternal",value:function(){var e=this,t=this.config,i=this.context;if(t&&i){var r=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===r&&!e.stats.aborted)return a(r,i.url)}).catch(function(t){if(e.loader===r&&!e.stats.aborted)return r.open("GET",i.url,!0),a(r,i.url)}).then(function(){e.loader!==r||e.stats.aborted||e.openAndSendXhr(r,i,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:r.status,text:t.message},i,r,n)}):this.openAndSendXhr(r,i,t)}}},{key:"openAndSendXhr",value:function(e,t,i){e.readyState||e.open("GET",t.url,!0);var r=t.headers,n=i.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(r)for(var o in r)e.setRequestHeader(o,r[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),i.timeout=a&&X(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,i=this.stats;if(e&&t){var r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),4===r)){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;i.loading.end=Math.max(self.performance.now(),i.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;i.loaded=i.total=c,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(i,e,o,t);var h={url:t.responseURL,data:o,code:a};return void(null==(u=this.callbacks)||u.onSuccess(h,i,e,t))}}var f,v=n.loadPolicy.errorRetry;if(ci(v,i.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else Te.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,i)}}}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(ci(e,this.stats.retry,!0))this.retry(e);else{var t;Te.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}}},{key:"retry",value:function(e){var t=this.context,i=this.stats;this.retryDelay=li(e,i.retry),i.retry++,Te.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==t?void 0:t.url,", retrying ").concat(i.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&&Yl.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:Ti,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:kr,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:Hl,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:Wo,subtitleTrackController:wo,timelineController:Nl,audioStreamController:as,audioTrackController:cs,emeController:po,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,i){return t[i]=Ql(e[i]),t},{}):e}function $l(e,t){var i=e.loader;i!==jl&&i!==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,i){var r;return a(this,t),(r=n(this,t,["gap-controller",e.logger])).hls=void 0,r.fragmentTracker=void 0,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var e;null!=(e=r.media)&&e.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var e;r.hls&&(r.ended=(null==(e=r.media)?void 0:e.currentTime)||1,r.hls.trigger(ee.MEDIA_ENDED,{stalled:!1}))},r.hls=e,r.fragmentTracker=i,r.registerListeners(),r}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 i=this.media=t.media;ln(i,"playing",this.onMediaPlaying),ln(i,"waiting",this.onMediaWaiting),ln(i,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var i=this.media;i&&(un(i,"playing",this.onMediaPlaying),un(i,"waiting",this.onMediaWaiting),un(i,"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 i,r,n=null==(i=this.hls)?void 0:i.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(ji.getBuffered(a).length){var c=ji.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 m=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!d)return;var p=Math.max(d,c.start||0)-e,y=!(null==m||!m.live)?2*m.targetduration:2,E=tu(e,h);if(p>0&&(p<=y||E))return void(a.paused||this._trySkipBufferHole(E))}var T=n.detectStallWithCurrentTimeMs,k=self.performance.now(),S=this.waiting,A=this.stalled;if(null===A){if(!(S>0&&k-S<T))return void(this.stalled=k);A=this.stalled=S}var b=k-A;if(!s&&(b>=T||S)&&this.hls){var L;if("ended"===(null==(L=this.mediaSource)?void 0:L.readyState)&&(null==m||!m.live)&&Math.abs(e-((null==m?void 0:m.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=ji.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(I,b,e)}else this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(i),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(ee.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){var n=ji.bufferedInfo(ji.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=ji.timeRangesToArray(r),s=ji.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=ji.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=ji.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,i){var r,n,a=this.fragmentTracker,s=this.media,o=null==(r=this.hls)?void 0:r.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=tu(i,a);if(u||null!=l&&l.live&&i<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,i);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<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 i=this.fragmentTracker,r=e.nextStart;if(i&&r){var n=i.getFragAtPos(t,ae),a=i.getFragAtPos(r,ae);if(n&&a)return a.sn-n.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,i=this.media,r=this.stallReported,n=this.stalled;if(!r&&null!==n&&i&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(i.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,i=this.fragmentTracker,r=this.media,n=null==(t=this.hls)?void 0:t.config;if(!r||!i||!n)return 0;var a=r.currentTime,s=ji.bufferInfo(r,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&&r.readyState<3,c=o-a;if(c>0&&(l||u)){if(c>n.maxBufferHole){var d=!1;if(0===a){var h=i.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 m=tu(g,i);if(!m){v=!0;break}g+=m.duration}if(v)return 0}}var p=Math.max(o+.05,a+.1);if(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(p)),this.moved=!0,r.currentTime=p,null==e||!e.gap){var y=new Error("fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(p)),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 p}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,i=this.media,r=this.nudgeRetry,n=null==t?void 0:t.config;if(!i||!n)return 0;var a=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){var s=a+(r+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),i.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})}}}])}(Vi);function Zl(e,t){var i=eu(e.main);if(i&&i.start<=t)return i;var r=eu(e.audio);return r&&r.start<=t?r:null}function eu(e){if(!e)return null;switch(e.state){case hn:case dn:case En:case Tn:return null}return e.frag}function tu(e,t){return t.getAppendedFrag(e,ae)||t.getPartialFragment(e)}function iu(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ru(e,t,i,r,n){var a=new e(t,i,"");try{a.value=r,n&&(a.type=n)}catch(s){a=new e(t,i,Kt(n?fe({type:n},r):r))}return a}var nu=function(){var e=iu();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 i=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(){i.hls&&i.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 i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.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 i=e[t];if("metadata"===i.kind&&"id3"===i.label)return Ao(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var i=this.hls.config,r=i.enableEmsgMetadataCues,n=i.enableID3MetadataCues;if(r||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=iu();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==Zn.emsg||r)&&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=ru(s,c,d,f,l);v&&this.id3Track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var n=r.length;n--;){var a=r[n];a.type===t&&a.startTime<e&&a.endTime===nu&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var i=t.startOffset,r=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,i,r,"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 i=t.details;this.updateDateRangeCues(i,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var i=this;if(this.hls&&this.media){var r=this.hls.config,n=r.assetPlayerId,a=r.timelineOffset,s=r.enableDateRangeMetadataCues,o=r.interstitialsController;if(s){var l=iu();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=ru(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),m=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.cues)&&h.length)for(var p,y=Object.keys(m).filter(function(e){return!g.includes(e)}),E=function(){var e=y[T],t=null==(p=m[e])?void 0:p.cues;delete m[e],t&&Object.keys(t).forEach(function(e){var r=t[e];if(r){r.removeEventListener("enter",i.onEventCueEnter);try{f.removeCue(r)}catch(e){}}})},T=y.length;T--;)E();else m=this.dateRangeCuesAppended={};var k=e.fragments[e.fragments.length-1];if(0!==g.length&&X(null==k?void 0:k.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=g[A],t=v[e],r=t.startTime,n=m[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=r+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,i){if(i!==t.id){var r=v[i];if(r.class===t.class&&r.startDate>t.startDate&&(!e||t.startDate<e.startDate))return r}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var p=h[f];if(Zi(p)){var y=a[p];if(y)!s||null!=n&&n.durationKnown?Math.abs(y.startTime-r)>.01&&(y.startTime=r,y.endTime=u):y.endTime=u;else if(l){var E=t.attr[p];er(p)&&(E=Le(E));var T=ru(l,r,u,{key:p,data:E},Zn.dateRange);T&&(T.id=e,i.id3Track.addCue(T),a[p]=T,o&&("X-ASSET-LIST"!==p&&"X-ASSET-URL"!==p||T.addEventListener("enter",i.onEventCueEnter)))}}}m[e]={cues:a,dateRange:t,durationKnown:s}},A=0;A<g.length;A++)S()}}}}}}])}(),su=function(){return o(function e(t){var i=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=i.media,t=i.levelDetails;if(e&&t){i.currentTime=e.currentTime;var r=i.computeLatency();if(null!==r){i._latency=r;var n=i.config,a=n.lowLatencyMode,s=n.maxLiveSyncPlaybackRate;if(a&&1!==s&&t.live){var o=i.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(i.maxLatency,o+t.targetduration)&&l>.05&&i.forwardBufferLength>1){var u=Math.min(2,Math.max(1,s)),c=Math.round(2/(1+Math.exp(-.75*l-i.edgeStalled))*20)/20,d=Math.min(u,Math.max(1,c));i.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&i.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,i=e.partHoldBack,r=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*r);var c=r;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 i=this.levelDetails;if(null===i)return null;var r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,s=r-(this.config.lowLatencyMode&&i.partTarget||i.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 i=e.buffered.length;return(i?e.buffered.end(i-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 i=t.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onError",value:function(e,t){var i;t.details===Z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(r=this.targetLatency)?void 0:r.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,i){var r;return a(this,t),(r=n(this,t,[e,"level-controller"]))._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,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.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 i=this,r=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=kt(c,r)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),i=0;i<t.length;i++){var r=t[i].split(".");r.length>2&&"avc1"===r[0]&&(t[i]="avc1.".concat(parseInt(r[1]).toString(16)).concat(("000"+parseInt(r[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&&!i.isAudioSupported(c)||d&&!i.isVideoSupported(d))i.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'));else{var m=t.CODECS,p=t["FRAME-RATE"],y=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],T=t.RESOLUTION,k=t["VIDEO-RANGE"],S="".concat(E||".","-"),A="".concat(S).concat(e.bitrate,"-").concat(T,"-").concat(p,"-").concat(m,"-").concat(k,"-").concat(y);if(a[A])if(a[A].uri===e.url||e.attrs["PATHWAY-ID"])a[A].addGroupId("audio",t.AUDIO),a[A].addGroupId("text",t.SUBTITLES);else{var b=s[A]+=1;e.attrs["PATHWAY-ID"]=new Array(b+1).join(".");var L=i.createLevel(e);a[A]=L,n.push(L)}else{var I=i.createLevel(e);a[A]=I,s[A]=1,n.push(I)}}}),this.filterAndSortMediaOptions(n,t,o,l,u)}},{key:"createLevel",value:function(e){var t=new Gt(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(i.videoCodec,'"'));this.log(r.message),t.supportedResult=Pt(r,[])}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,i,r,n){var a,s=this,o=[],l=[],u=e,c=(null==(a=t.stats)?void 0:a.parsing)||{};if((i||r)&&n&&(u=u.filter(function(e){var t,i=e.videoCodec,r=e.videoRange,n=e.width,a=e.height;return(!!i||!(!n||!a))&&(!!(t=r)&&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",i=e;t.levels.length&&(i="one or more CODECS in variant not supported: ".concat(Kt(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,i){return i.indexOf(e)===t}))),s.warn(i),e+=" (".concat(i,")"));var r=new Error(e);s.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}),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(i&&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 r=pt(e.videoCodec),n=pt(t.videoCodec);if(r!==n)return n-r}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 m=h.bitrate,p=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(u.length," level(s) found, first bitrate: ").concat(m)),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){var y=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);y>p&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var E=n&&!r,T=this.hls.config,k=!(!T.audioStreamController||!T.audioTrackController),S={levels:u,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:k&&!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 i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)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(),i=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=i}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ie&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var i=t.frag;if(void 0!==i&&i.type===ae){var r=i.elementaryStreams;if(!Object.keys(r).some(function(e){return!!r[e]}))return;var n=this._levels[i.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 i,r,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(n)),void(null!=(r=t.deliveryDirectives)&&r.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!=(i=t.deliveryDirectives)&&i.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,i){E(t,"loadingPlaylist",this,3)([e,i]);var r=this.getUrlWithDirectives(e.uri,i),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==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(r)),this.hls.trigger(ee.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||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,i=this;if(1!==this._levels.length){var r=this._levels.filter(function(t,r){return r!==e||(i.steering&&i.steering.removeLevel(t),t===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});Zr(r),this._levels=r,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=r.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:r})}}},{key:"onLevelsUpdated",value:function(e,t){var i=t.levels;this._levels=i}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,i=e.maxAutoLevel,r=e.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(ee.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}])}(ss);function lu(e){var t={};e.forEach(function(e){var i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function uu(){return self.SourceBuffer||self.WebKitSourceBuffer}function cu(){if(!ke())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,i,r){var s;return a(this,t),(s=n(this,t,[e,i,r,"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 i=s.getFwdBufferInfoAtPos(e,t,ae,0);null!==i&&0!==i.len?s.tick():s.warn("Main forward buffer length at ".concat(t,' on "seeked" event ').concat(i?i.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 i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=r.startLevel;-1===n&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @".concat(i.toFixed(3))),e=i),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,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))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,i=this.levels,r=this.media;if(null!==t&&(r||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=i&&i[n]){var a=i[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)!==Li){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,m=u.fragments[g-1];m&&f.cc===m.cc&&(f=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var p=this.audioOnly&&!this.altAudio?Ce:_e,y=(p===_e?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p,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,i,r){var n=this.fragmentTracker.getState(e);n===Si||n===bi?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,i)):E(t,"loadFragment",this,3)([e,i,r]):this._loadInitSegment(e,i):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 i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.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;i=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(t.currentTime+i);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 pn:case yn:this.state=hn}this.nextLoadPosition=this.getLoadPosition()}},{key:"flushMainBuffer",value:function(e,i){E(t,"flushMainBuffer",this,3)([e,i,2===this.altAudio?"video":null])}},{key:"onMediaAttached",value:function(e,i){E(t,"onMediaAttached",this,3)([e,i]);var r=i.media;ln(r,"playing",this.onMediaPlaying),ln(r,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,i){var r=this.media;r&&(un(r,"playing",this.onMediaPlaying),un(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,E(t,"onMediaDetaching",this,3)([e,i]),!!i.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 i,r,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==(r=uu())||null==(i=r.prototype)?void 0:i.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 i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Sn)}}},{key:"onLevelLoaded",value:function(e,t){var i,r=this.levels,n=this.startFragRequested,a=t.level,s=t.details,o=s.totalduration;if(r){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!=(i=l.details)&&i.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,i=this.media;if(i){var r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==r&&i.duration>r&&(n<r||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.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(r.toFixed(3))),"buffered"===this.config.liveSyncMode){var u,c=ji.bufferInfo(i,r,0);if(null==(u=c.buffered)||!u.length)return void(i.currentTime=r);if(c.start<=n)return void(i.currentTime=r);var d=ji.bufferedInfo(c.buffered,n,0).nextStart;d&&(i.currentTime=d)}else i.currentTime=r}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,i=e.frag,r=e.part,n=e.payload,a=this.levels;if(a){var s=a[i.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(i.sn," of level ").concat(i.level," after level details were reset")),void this.fragmentTracker.removeFragment(i);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=i.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=r?r.index:-1,v=-1!==f,g=new Hi(i.level,i.sn,i.stats.chunkCount,n.byteLength,f,v),m=this.initPTS[i.cc];h.push(n,c,d,l,i,r,o.totalduration,u,g,m)}else this.warn("Level ".concat(i.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(i.sn," of level ").concat(i.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var i=this,r=this.hls,n=0!==this.altAudio;if($t(t.url,r))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.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(ee.BUFFER_FLUSHED,function(){i.hls&&i.hls.trigger(ee.AUDIO_TRACK_SWITCHED,t)}),void r.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(ee.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var i=$t(t.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()}},{key:"onBufferCreated",value:function(e,t){var i,r,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(r=s,i=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&i?(this.log("Alternate track found, use ".concat(r,".buffered to schedule main fragment loading")),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var i=t.frag,r=t.part,n=i.type===ae;if(n){if(this.fragContextChanged(i))return this.warn("Fragment ".concat(i.sn).concat(r?" p: "+r.index:""," of level ").concat(i.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===yn&&(this.state=hn));var a=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Oe(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var s=this.media;s&&(!this._hasEnoughToStart&&ji.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 i;if(t.fatal)this.state=Tn;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==(i=t.context)?void 0:i.type)!==ie||(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 i=t.type;if(i!==Ce||!this.altAudio){var r=(i===_e?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,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,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log("could not seek to ".concat(i,", already seeking at ").concat(t));var r=this.timelineOffset;r&&i&&(i+=r);var n=this.getLevelDetails(),a=ji.getBuffered(e),s=a.length?a.start(0):0,o=s-i,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")),i+=o,this.startPosition=i),t<i&&(this.log("seek to target start position ".concat(i," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=i)}}}},{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 i=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var r=i.hls,n=null==e?void 0:e.frag;if(n&&!i.fragContextChanged(n)){t.fragmentError=0,i.state=hn,i.startFragRequested=!1,i.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(ee.FRAG_LOADED,e),n.bitrateTest=!1}}).catch(function(t){i.state!==dn&&i.state!==Tn&&(i.warn(t),i.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,i=this.hls,r=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=r.video,c=r.text,d=r.id3,h=r.initSegment,f=l.details,v=this.altAudio?void 0:r.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=pn,h){var g=h.tracks;if(g){var m=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,m,n),i.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:t,tracks:g})}var p=h.initPTS,y=h.timescale,E=this.initPTS[s.cc];if(X(p)&&(!E||E.baseTime!==p||E.timescale!==y)){var T=h.trackId;this.initPTS[s.cc]={baseTime:p,timescale:y,trackId:T},i.trigger(ee.INIT_PTS_FOUND,{frag:s,id:t,initPTS:p,timescale:y,trackId:T})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var k=f.fragments[s.sn-1-f.startSN],S=s.sn===f.startSN,A=!k||s.cc>k.cc;if(!1!==r.independent){var b=u.startPTS,L=u.endPTS,I=u.startDTS,R=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:b,endPTS:L,startDTS:I,endDTS:R};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!A&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),P=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:b;if(!S&&P<D-this.config.maxBufferHole&&!A)return void this.backtrack(s);A&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,L,s.start,R,!0)}else S&&b-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,b,L,I,R),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,S||A)}else{if(!S&&!A)return void this.backtrack(s);s.gap=!0}}if(v){var C=v.startPTS,_=v.endPTS,x=v.startDTS,M=v.endDTS;o&&(o.elementaryStreams[Ce]={startPTS:C,endPTS:_,startDTS:x,endDTS:M}),s.setElementaryStreamInfo(Ce,C,_,x,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};i.trigger(ee.FRAG_PARSING_METADATA,O)}if(f&&c){var F={id:t,frag:s,details:f,samples:c.samples};i.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,i,r){var n=this;if(this.state===pn){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));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:i,part:null,chunkMeta:r,parent:i.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,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.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 i=e.currentTime;if(ji.isBuffered(e,i)?t=this.getAppendedFrag(i):ji.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;var r=this.fragPlaying,n=t.level;r&&t.sn===r.sn&&r.level===n||(this.fragPlaying=t,this.hls.trigger(ee.FRAG_CHANGED,{frag:t}),r&&r.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 i=this.getLevelDetails(),r=this.currentFrag||(i?ei(null,i.fragments,t):null);if(r){var n=r.programDateTime;if(null!==n){var a=n+1e3*(t-r.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}}])}(An),hu=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,["key-loader",i])).config=void 0,r.keyIdToKeyInfo={},r.emeController=null,r.config=e,r}return d(t,e),o(t,[{key:"abort",value:function(e){for(var t in this.keyIdToKeyInfo){var i=this.keyIdToKeyInfo[t].loader;if(i){var r;if(e&&e!==(null==(r=i.context)?void 0:r.frag.type))return;i.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,i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;return new Gi({type:J.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}},{key:"loadClear",value:function(e,t,i){var r=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)||!i&&s==o-1)return{v:r.emeController.selectKeySystemFormat(n).then(function(e){if(r.emeController){n.setKeyFormat(e);var t=pr(e);return t?r.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=Er(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(i){return t.loadInternal(e,i)}):this.loadInternal(e)}},{key:"loadInternal",value:function(e,t){var i,r;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!=(i=l)&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(r=l)&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(function(t){var i=t.keyInfo;return n.key=i.decryptdata.key,{frag:e,keyInfo:i}})}switch(this.log("".concat(this.keyIdToKeyInfo[o]?"Rel":"L","oading").concat(n.keyId?" keyId: "+be(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 i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&null!=(r=t.initSegment)&&r.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(be(a))),br.setKeyIdForUri(e.decryptdata.uri,a)):(a=br.addKeyIdForUri(e.decryptdata.uri),this.log("Generating keyId to patch media ".concat(be(a)))),e.decryptdata.keyId=a}}if(!e.decryptdata.keyId&&!Oe(t))return Promise.resolve(i);var s=this.emeController.loadKey(i);return(e.keyLoadPromise=s.then(function(t){return e.mediaKeySessionContext=t,i})).catch(function(i){throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i})}return Promise.resolve(i)}},{key:"loadKeyHTTP",value:function(e,t){var i=this,r=this.config,n=new(0,r.loader)(r);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=r.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:function(e,t,r,n){var o=r.frag,l=r.keyInfo,u=fu(l.decryptdata);if(!o.decryptdata||l!==i.keyIdToKeyInfo[u])return s(i.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,r,n,a){i.resetLoader(r),s(i.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,r,n){i.resetLoader(r),s(i.createKeyLoadError(t,Z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:function(e,r,n){i.resetLoader(r),s(i.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,i=e.keyInfo,r=e.url,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);var a=fu(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}])}(ve);function fu(e){if(e.keyFormat!==vr){var t=e.keyId;if(t)return be(t)}return e.uri}function vu(e){switch(e.type){case re:return se;case ne:return oe;default:return ae}}function gu(e,t){var i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}var mu=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,i=t.pLoader,r=t.loader,n=new(i||r)(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 i=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te,url:i,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var i=t.id,r=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ie,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var i=t.id,r=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:re,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var i=t.id,r=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:ne,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var i=this.loaders[ie];if(i){var r=i.context;r&&!t.levels.some(function(e){return e===r.levelOrTrack})&&(i.abort(),delete this.loaders[ie])}}},{key:"load",value:function(e){var t,i,r,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((i=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===ie&&null!==e.level?r=this.hls.levels[e.level].details:e.type===re&&null!==e.id?r=this.hls.audioTracks[e.id].details:e.type===ne&&null!==e.id&&(r=this.hls.subtitleTracks[e.id].details),r)){var u=r.partTarget,c=r.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);i=de({},i,{maxTimeToFirstByteMs:Math.min(d,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,i.maxTimeToFirstByteMs)})}}var h=i.errorRetry||i.timeoutRetry||{},f={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,i,r){var a=n.getInternalLoader(i);n.resetInternalLoader(i.type);var s=e.data;t.parsing.start=performance.now(),Cr.isMediaPlaylist(s)||i.type!==te?n.handleTrackOrLevelPlaylist(e,t,i,r||null,a):n.handleMasterPlaylist(e,t,i,r)},onError:function(e,t,i,r){n.handleNetworkError(t,i,!1,e,r)},onTimeout:function(e,t,i){n.handleNetworkError(t,i,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,i=t.autoStartLoad,r=t.startPosition,n=e.forceStartLoad;(i||n)&&(this.hls.logger.log("".concat(i?"auto":"force"," startLoad with configured startPosition ").concat(r)),this.hls.startLoad(r))}}},{key:"handleMasterPlaylist",value:function(e,t,i,r){var n=this,a=this.hls,s=e.data,o=gu(e,i),l=Cr.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,i,l.playlistParsingError,r,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 i=n.hls.config.preferManagedMediaSource,r=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];vt(o,"audio",i)?(e.audioCodec=r=r?"".concat(r,",").concat(o):o,ht.audio[r.substring(0,4)]=2,t.splice(s,1)):vt(o,"video",i)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,ht.video[a.substring(0,4)]=2,t.splice(s,1))}});var g=Cr.parseMasterPlaylistMedia(s,o,l),m=g.AUDIO,p=void 0===m?[]:m,y=g.SUBTITLES,E=g["CLOSED-CAPTIONS"];p.length&&(p.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"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ji({}),bitrate:0,url:""})));a.trigger(ee.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:y,captions:E,contentSteering:u,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:v})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,i,r,n){var a=this.hls,s=i.id,o=i.level,l=i.type,u=gu(e,i),c=X(o)?o:X(s)?s:0,d=vu(i),h=Cr.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===te){var f={attrs:new Ji({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Xr(h,0),a.trigger(ee.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=h,this.handlePlaylistLoaded(h,e,t,i,r,n)}},{key:"handleManifestParsingError",value:function(e,t,i,r,n){this.hls.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.MANIFEST_PARSING_ERROR,fatal:t.type===te,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})}},{key:"handleNetworkError",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,a="A network ".concat(i?"timeout":"error"+(r?" (status "+r.code+")":"")," occurred while loading ").concat(e.type);e.type===ie?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==re&&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=i?Z.MANIFEST_LOAD_TIMEOUT:Z.MANIFEST_LOAD_ERROR,l=!0;break;case ie:o=i?Z.LEVEL_LOAD_TIMEOUT:Z.LEVEL_LOAD_ERROR,l=!1;break;case re:o=i?Z.AUDIO_TRACK_LOAD_TIMEOUT:Z.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ne:o=i?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(r){var d=(null==t?void 0:t.url)||e.url;c.response=fe({url:d,data:void 0},r)}this.hls.trigger(ee.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,i,r,n,a){var s=this.hls,o=r.type,l=r.level,u=r.levelOrTrack,c=r.id,d=r.groupId,h=r.deliveryDirectives,f=gu(t,r),v=vu(r),g="number"==typeof r.level&&v===ae?l:void 0,m=e.playlistParsingError;if(m){if(this.hls.logger.warn("".concat(m," ").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:m,reason:m.message,response:t,context:r,level:g,parent:v,networkDetails:n,stats:i});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 ie:if(g)if(u){if(u!==s.levels[g]){var p=s.levels.indexOf(u);p>-1&&(g=p)}}else g=0;s.trigger(ee.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:o===te});break;case re:s.trigger(ee.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:h});break;case ne:s.trigger(ee.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:i,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:r,level:g,parent:v,networkDetails:n,stats:i})}}}])}(),pu=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 i=this.logger=function(e,t,i){var r=pe();if("object"===("undefined"==typeof console?"undefined":S(console))&&!0===e||"object"===S(e)){var n=["debug","log","info","warn","error"];n.forEach(function(t){r[t]=ye(t,e,i)});try{r.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.6.15"))}catch(e){return pe()}n.forEach(function(t){Ee[t]=ye(t,e)})}else de(Ee,r);return r}(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(e,t,i){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 r=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(i){var n="".concat(e,"Loading").concat(i),l=t[n];if(void 0!==l&&s){o.push(n);var u=r[a].default;switch(t[a]={default:u},i){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&&i.warn('hls.js config: "'.concat(o.join('", "'),'" setting(s) are deprecated, use "').concat(a,'": ').concat(Kt(t[a])))}),fe(fe({},r),t)}(e.DefaultConfig,t,i);this.userConfig=t,r.progressive&&$l(r,i);var n=r.abrController,s=r.bufferController,o=r.capLevelController,l=r.errorController,u=r.fpsController,c=new l(this),d=this.abrController=new n(this),h=new Ii(this),f=r.interstitialsController,v=f?this.interstitialsController=new f(this,e):null,g=this.bufferController=new s(this,h),m=this.capLevelController=new o(this),p=new u(this),y=new mu(this),E=r.contentSteeringController,T=E?new E(this):null,k=this.levelController=new ou(this,T),A=new au(this),b=new hu(this.config,this.logger),L=this.streamController=new du(this,h,b),I=this.gapController=new Jl(this,h);m.setStreamController(L),p.setStreamController(L);var R=[y,k,L];v&&R.splice(1,0,v),T&&R.splice(1,0,T),this.networkControllers=R;var w=[d,g,I,m,p,A,h];this.audioTrackController=this.createController(r.audioTrackController,R);var P=r.audioStreamController;P&&R.push(this.audioStreamController=new P(this,h,b)),this.subtitleTrackController=this.createController(r.subtitleTrackController,R);var D=r.subtitleStreamController;D&&R.push(this.subtititleStreamController=new D(this,h,b)),this.createController(r.timelineController,w),b.emeController=this.emeController=this.createController(r.emeController,w),this.cmcdController=this.createController(r.cmcdController,w),this.latencyController=this.createController(su,w),this.coreComponents=w,R.push(c);var C=c.onErrorOut;"function"==typeof C&&this.on(ee.ERROR,C,c),this.on(ee.MANIFEST_LOADED,y.onManifestLoaded,y)}return o(e,[{key:"createController",value:function(e,t){if(e){var i=new e(this);return t&&t.push(i),i}return null}},{key:"on",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,i)}},{key:"once",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,i)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,r=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,i,r)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,i){return this._emitter.emit(e,t,i)}},{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 i=e===ee.ERROR;this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:i,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 i="media"in e,r=i?e.media:e,n=i?e:{media:r};this._media=r,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,i=this._url,r=this._url=Pe.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(r)),t&&i&&(i!==r||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 i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}},{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(r){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(i+16*Math.random())%16|0;return i=Math.floor(i/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 xt.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 i=e.length,r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=r)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 Dt(e,Wt(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return Dn}},{key:"isMSESupported",value:function(){return cu()}},{key:"isSupported",value:function(){return function(){if(!cu())return!1;var e=ke();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(mt(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(mt(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return ke()}},{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}}])}();pu.defaultConfig=void 0;var yu="https://sspproxy.adstorm.co/openrtb2/auction/adstorm";function Eu(e){var t;void 0===e&&(e={});var i=!1,r=null!==(t=e.debug)&&void 0!==t&&t;function n(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r&&console.log.apply(console,M(["[Prebid]"],x(e),!1))}function a(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,M(["[Prebid]"],x(e),!1))}function s(){return D(this,void 0,void 0,function(){var e,t,s,o,l,u,c,d,h,f,v,g,m,p,y,E;return C(this,function(T){switch(T.label){case 0:if(!i)throw new Error("Prebid not initialized. Call initialize() first.");e=3e3,n("Fetching auction response from:",yu),t="undefined"!=typeof AbortController?new AbortController:null,s=setTimeout(function(){null==t||t.abort()},e+2e3),T.label=1;case 1:return T.trys.push([1,6,,7]),o={method:"POST"},t&&(o.signal=t.signal),[4,fetch(yu,o)];case 2:return l=T.sent(),clearTimeout(s),l.ok?[3,4]:[4,l.text().catch(function(){return""})];case 3:throw u=T.sent(),new Error("Prebid Server returned HTTP ".concat(l.status,": ").concat(u.slice(0,200)));case 4:return[4,l.json()];case 5:if(c=T.sent(),r&&(null===(y=null==c?void 0:c.ext)||void 0===y?void 0:y.responsetimemillis)&&n("Bidder response times:",c.ext.responsetimemillis),r&&(null===(E=null==c?void 0:c.ext)||void 0===E?void 0:E.errors)&&a("Auction errors:",c.ext.errors),d=function(e){var t,i,r,n,a,s,o,l,u=[],c=(null==e?void 0:e.seatbid)||[],d=(null==e?void 0:e.cur)||"USD";try{for(var h=_(c),f=h.next();!f.done;f=h.next()){var v=f.value,g=v.seat||"unknown",m=v.bid||[];try{for(var p=(r=void 0,_(m)),y=p.next();!y.done;y=p.next()){var E=y.value,T=null===(l=null===(o=null===(s=null===(a=E.ext)||void 0===a?void 0:a.prebid)||void 0===s?void 0:s.cache)||void 0===o?void 0:o.vastXml)||void 0===l?void 0:l.url,k=E.adm||void 0,S={bidder:g,cpm:E.price||0,width:E.w||0,height:E.h||0,adId:E.id||"",impId:E.impid||"",creativeId:E.crid||"",currency:d};T&&(S.vastUrl=T),k&&(S.vastXml=k),E.adomain&&(S.adomain=E.adomain),u.push(S)}}catch(e){r={error:e}}finally{try{y&&!y.done&&(n=p.return)&&n.call(p)}finally{if(r)throw r.error}}}}catch(e){t={error:e}}finally{try{f&&!f.done&&(i=h.return)&&i.call(h)}finally{if(t)throw t.error}}return u.sort(function(e,t){return t.cpm-e.cpm}),u}(c),n("Received ".concat(d.length," bid(s)")),r)try{for(h=_(d),f=h.next();!f.done;f=h.next())v=f.value,n(" ".concat(v.bidder,": $").concat(v.cpm.toFixed(2)," ").concat(v.currency)+" ".concat(v.width,"x").concat(v.height)+(v.vastUrl?" [cached VAST]":"")+(v.vastXml&&!v.vastUrl?" [VAST XML]":""))}catch(e){m={error:e}}finally{try{f&&!f.done&&(p=h.return)&&p.call(h)}finally{if(m)throw m.error}}return[2,d];case 6:if(g=T.sent(),clearTimeout(s),"AbortError"===(null==g?void 0:g.name))return a("Auction request timed out after ".concat(e+2e3,"ms")),[2,[]];throw g;case 7:return[2]}})})}return{initialize:function(){return D(this,void 0,void 0,function(){return C(this,function(e){return i||(i=!0,n("Initialized, auction URL:",yu)),[2]})})},requestBids:s,requestBidsUntilResponse:function(){return D(this,void 0,void 0,function(){var e,t,r,o;return C(this,function(l){switch(l.label){case 0:if(!i)throw new Error("Prebid not initialized. Call initialize() first.");t=function(t){var i,r,o;return C(this,function(l){switch(l.label){case 0:return l.trys.push([0,2,,3]),[4,s()];case 1:return(i=l.sent()).length>0?(n("requestBidsUntilResponse: got ".concat(i.length," bid(s) on attempt ").concat(t)),[2,{value:i}]):(n("requestBidsUntilResponse: no bids on attempt ".concat(t,"/").concat(3)),[3,3]);case 2:return r=l.sent(),e=r,a("requestBidsUntilResponse: attempt ".concat(t,"/").concat(3," failed:"),r),[3,3];case 3:return t<3?(n("requestBidsUntilResponse: waiting ".concat(o=1500*t,"ms before retry")),[4,new Promise(function(e){return setTimeout(e,o)})]):[3,5];case 4:l.sent(),l.label=5;case 5:return[2]}})},r=1,l.label=1;case 1:return r<=3?[5,t(r)]:[3,4];case 2:if("object"===S(o=l.sent()))return[2,o.value];l.label=3;case 3:return r++,[3,1];case 4:if(e instanceof Error)throw e;return[2,[]]}})})},destroy:function(){i=!1,n("Destroyed")},get isInitialized(){return i}}}function Tu(e){return"video/mp4"===e||e.includes("mp4")}function ku(e,t,i){var r,n,a,s;void 0===t&&(t="all"),void 0===i&&(i="[VastParser]");try{var o=(new DOMParser).parseFromString(e,"text/xml"),l=o.querySelector("parsererror");if(l)return console.error("".concat(i," XML parsing error (malformed VAST XML):"),l.textContent),null;var u=o.querySelector("Ad");if(!u)return console.warn("".concat(i," No Ad element found in VAST XML")),null;var c=u.getAttribute("id")||"unknown",d=(null===(r=o.querySelector("AdTitle"))||void 0===r?void 0:r.textContent)||"Ad",h="empty"===c||d.toLowerCase().includes("no ad available")||"no ad available"===d.toLowerCase(),f=((null===(n=o.querySelector("Duration"))||void 0===n?void 0:n.textContent)||"00:00:30").split(":"),v=3600*parseInt(f[0]||"0",10)+60*parseInt(f[1]||"0",10)+Math.round(parseFloat(f[2]||"0")),g=o.querySelectorAll("MediaFile"),m=[];if(console.log("".concat(i," Found ").concat(g.length," MediaFile element(s) in VAST XML")),g.forEach(function(e,r){var n,a=e.getAttribute("type")||"",s=(null===(n=e.textContent)||void 0===n?void 0:n.trim())||"",o=e.getAttribute("width")||"",l=e.getAttribute("height")||"";if(console.log("".concat(i," MediaFile ").concat(r,': type="').concat(a,'", url="').concat(s.substring(0,80),'...", width="').concat(o,'", height="').concat(l,'"')),s){var u=function(e){return"application/x-mpegURL"===e||e.includes("m3u8")}(a),c=Tu(a);if("hls-only"===t?u:"mp4-first"!==t||(c||u)){var d=e.getAttribute("bitrate"),h=d?parseInt(d,10):void 0;m.push({url:s,type:a,width:parseInt(o||"1920",10),height:parseInt(l||"1080",10),bitrate:h&&h>0?h:void 0}),console.log("".concat(i,' Added MediaFile: type="').concat(a,'" url="').concat(s.substring(0,80),'..."'))}else console.log("".concat(i," MediaFile ").concat(r,' ignored (type="').concat(a,'" not accepted by filter "').concat(t,'")'))}else console.warn("".concat(i," MediaFile ").concat(r," has empty URL"))}),"mp4-first"===t&&m.length>1&&m.sort(function(e,t){return(Tu(e.type)?0:1)-(Tu(t.type)?0:1)}),0===m.length)return h?console.warn("".concat(i," No ads available (VAST response indicates no ads)")):console.warn("".concat(i," No compatible media files found in VAST XML")),null;var p={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};o.querySelectorAll("Impression").forEach(function(e){var t,i=null===(t=e.textContent)||void 0===t?void 0:t.trim();i&&p.impression.push(i)}),o.querySelectorAll("Tracking").forEach(function(e){var t,i=e.getAttribute("event"),r=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(i&&r){var n=i;p[n]&&p[n].push(r)}});var y=null===(s=null===(a=o.querySelector("ClickThrough"))||void 0===a?void 0:a.textContent)||void 0===s?void 0:s.trim();return{id:c,title:d,duration:v,mediaFiles:m,trackingUrls:p,clickThrough:y}}catch(e){return console.error("".concat(i," Error parsing VAST XML:"),e),null}}var Su="[PrebidAdLayer]";function Au(e,t){if(e.vastXml){var i=ku(e.vastXml,"mp4-first",t);return Promise.resolve(i)}return e.vastUrl?function(e){return D(this,arguments,void 0,function(e,t,i){var r,n;return void 0===t&&(t="all"),void 0===i&&(i="[VastParser]"),C(this,function(a){switch(a.label){case 0:return[4,fetch(e,{mode:"cors",credentials:"include",headers:{Accept:"application/xml, text/xml, */*"},referrerPolicy:"no-referrer-when-downgrade"})];case 1:if(!(r=a.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(r.statusText));return[4,r.text()];case 2:return n=a.sent(),console.log("".concat(i," VAST XML received")),console.log("".concat(i," VAST XML content (first 2000 chars):"),n.substring(0,2e3)),[2,ku(n,t,i)]}})})}(e.vastUrl,"mp4-first",t):Promise.resolve(null)}function bu(e,t){var i,r,n,a,s,o,l,u=!1,c=!1,d=Math.max(0,Math.min(1,e.volume||1)),h=new Map,f=null==t?void 0:t.mainHlsInstance,v=null!==(i=null==t?void 0:t.continueLiveStreamDuringAds)&&void 0!==i&&i,g=null!==(r=null==t?void 0:t.debug)&&void 0!==r&&r,m=!1,p=!1,y={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function E(e,t){var i,r,n=h.get(e);if(n)try{for(var a=_(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("".concat(Su," Error in event listener for ").concat(e,":"),t)}}}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(i)throw i.error}}}function T(e){!function(e,t,i){void 0===i&&(i="[VastParser]"),e&&0!==e.length&&e.forEach(function(e){try{var r=e;t&&(r="".concat(r).concat(r.includes("?")?"&":"?","session_id=").concat(t));var n=new Image(1,1);n.onerror=function(){},n.src=r,console.log("".concat(i," Fired tracking pixel: ").concat(r))}catch(e){console.warn("".concat(i," Error firing tracking pixel:"),e)}})}(e,l,Su)}function k(e){var t,i;if(0===e.length)throw new Error("No media files available");var r=e[0];if(1===e.length)return r;var n=function(){if(!(null==f?void 0:f.levels))return null;var e=f.currentLevel;if(-1===e||!f.levels[e]){var t=f.loadLevel;if(-1!==t&&f.levels[t]){var i=f.levels[t];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}return null}var r=f.levels[e];return{width:r.width||1920,height:r.height||1080,bitrate:r.bitrate||5e6}}();if(!n)return g&&console.log("".concat(Su," No main stream quality info, using first media file")),r;var a=e.map(function(e){var t=Math.abs(e.width-n.width)+Math.abs(e.height-n.height),i=1e3*(e.bitrate||5e3);return{file:e,score:2*t+Math.abs(i-n.bitrate)/1e3}});return a.sort(function(e,t){return e.score-t.score}),null!==(i=null===(t=a[0])||void 0===t?void 0:t.file)&&void 0!==i?i:r}function S(){n&&(n.addEventListener("timeupdate",function(){var e=o;if(e&&n){var t=n.currentTime/e.duration;t>=.25&&!y.firstQuartile&&(y.firstQuartile=!0,T(e.trackingUrls.firstQuartile)),t>=.5&&!y.midpoint&&(y.midpoint=!0,T(e.trackingUrls.midpoint)),t>=.75&&!y.thirdQuartile&&(y.thirdQuartile=!0,T(e.trackingUrls.thirdQuartile))}}),n.addEventListener("playing",function(){var e=o;e&&!y.start&&(y.start=!0,T(e.trackingUrls.start),g&&console.log("".concat(Su," Ad started playing")))}),n.addEventListener("ended",function(){p||!o||y.complete||(y.complete=!0,T(o.trackingUrls.complete),g&&console.log("".concat(Su," Ad completed")),function(){if(p)return;g&&console.log("".concat(Su," Handling ad completion"));u=!1,A(!1),s&&(s.style.display="none",s.style.pointerEvents="none");E("ad_impression"),E("content_resume")}())}),n.addEventListener("error",function(e){p||(console.error("".concat(Su," Ad video error:"),e),o&&T(o.trackingUrls.error),b())}),n.addEventListener("volumechange",function(){o&&n&&(n.muted?T(o.trackingUrls.mute):T(o.trackingUrls.unmute))}),n.addEventListener("pause",function(){o&&n&&!n.ended&&T(o.trackingUrls.pause)}),n.addEventListener("play",function(){o&&n&&n.currentTime>0&&T(o.trackingUrls.resume)}))}function A(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function b(){p||(g&&console.log("".concat(Su," Handling ad error")),u=!1,A(!1),s&&(s.style.display="none",s.style.pointerEvents="none"),E("ad_error"))}function L(){a&&(a.destroy(),a=void 0),n&&(n.pause(),n.removeAttribute("src"),n.load())}function I(e){var t;n&&("application/x-mpegURL"===(t=e).type||t.type.includes("m3u8")?function(e){n&&(g&&console.log("".concat(Su," Starting HLS playback: ").concat(e.url)),pu.isSupported()?(a&&(a.destroy(),a=void 0),(a=new pu({enableWorker:!0,lowLatencyMode:!1})).loadSource(e.url),a.attachMedia(n),a.on(pu.Events.MANIFEST_PARSED,function(){n.play().catch(function(e){console.error("".concat(Su," Error starting HLS ad playback:"),e),b()})}),a.on(pu.Events.ERROR,function(e,t){t.fatal&&b()})):n.canPlayType("application/vnd.apple.mpegurl")?(n.src=e.url,n.play().catch(function(e){console.error("".concat(Su," Error starting native HLS ad playback:"),e),b()})):(console.error("".concat(Su," HLS not supported on this platform")),b()))}(e):function(e){n&&(g&&console.log("".concat(Su," Starting native MP4 playback: ").concat(e.url)),n.src=e.url,n.load(),n.play().catch(function(e){console.error("".concat(Su," Error starting native ad playback:"),e),b()}))}(e))}return{initialize:function(){g&&console.log("".concat(Su," Initializing"))},updateOptions:function(e){var t;void 0!==e.continueLiveStreamDuringAds&&(v=e.continueLiveStreamDuringAds),void 0!==e.mainHlsInstance&&(f=null!==(t=e.mainHlsInstance)&&void 0!==t?t:void 0)},playAd:function(t){return D(this,void 0,void 0,function(){var i,r,a,h,f,p,b;return C(this,function(R){switch(R.label){case 0:return m?[2,Promise.reject(new Error("Layer has been destroyed"))]:0===t.length?[2,Promise.reject(new Error("No bids provided"))]:(i=t[0],g&&console.log("".concat(Su," Winning bid: ").concat(i.bidder," $").concat(i.cpm.toFixed(2)," ").concat(i.currency)),[4,Au(i,Su)]);case 1:return(r=R.sent())?(g&&console.log("".concat(Su," Ad parsed: ").concat(r.title,", duration: ").concat(r.duration,"s, mediaFiles: ").concat(r.mediaFiles.length)),l="session-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),o=r,y=w({},{impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1}),T(r.trackingUrls.impression),y.impression=!0,s||((a=document.createElement("div")).style.position="absolute",a.style.left="0",a.style.top="0",a.style.right="0",a.style.bottom="0",a.style.display="none",a.style.alignItems="center",a.style.justifyContent="center",a.style.pointerEvents="none",a.style.zIndex="10",a.style.backgroundColor="#000",null===(b=e.parentElement)||void 0===b||b.appendChild(a),s=a),n?L():((P=document.createElement("video")).style.position="absolute",P.style.left="0",P.style.top="0",P.style.width="100%",P.style.height="100%",P.style.objectFit="contain",P.style.backgroundColor="#000",P.playsInline=!0,P.muted=!1,P.volume=1,n=P,s.appendChild(n),S()),h=e.volume,d=Math.max(0,Math.min(1,h||d)),v||e.pause(),e.muted=!0,e.volume=0,u=!0,A(!0),f=c?1:d,n.volume=Math.max(0,Math.min(1,f)),n.muted=!1,s&&(s.style.display="flex",s.style.pointerEvents="auto"),E("content_pause"),p=k(r.mediaFiles),g&&console.log("".concat(Su," Loading ad from: ").concat(p.url)),I(p),[2]):(g&&console.warn("".concat(Su," Winning bid has no VAST URL or XML")),E("ad_error"),[2,Promise.reject(new Error("No VAST from bid"))])}var P})})},pause:function(){if(u&&n)try{n.paused||n.pause()}catch(e){g&&console.warn("".concat(Su," Error pausing ad:"),e)}},resume:function(){if(u&&n)try{n.paused&&n.play().catch(function(){})}catch(e){g&&console.warn("".concat(Su," Error resuming ad:"),e)}},stop:function(){return D(this,void 0,void 0,function(){return C(this,function(t){return p=!0,g&&console.log("".concat(Su," Stopping ad")),u=!1,A(!1),e.muted=c,e.volume=c?0:d,s&&(s.style.display="none",s.style.pointerEvents="none"),e.style.visibility="visible",e.style.opacity="1",v&&e.play().catch(function(){}),L(),n&&(n.pause(),n.removeAttribute("src"),n.load()),o=void 0,p=!1,[2]})})},destroy:function(){p=!0,g&&console.log("".concat(Su," Destroying")),m=!0,u=!1,A(!1),e.muted=c,e.volume=d,L(),n&&(n.pause(),n.removeAttribute("src"),n.remove(),n=void 0),(null==s?void 0:s.parentElement)&&s.parentElement.removeChild(s),s=void 0,o=void 0,h.clear()},isAdPlaying:function(){return u},resize:function(e,t){s&&(s.style.width="".concat(e,"px"),s.style.height="".concat(t,"px")),n&&(n.style.width="".concat(e,"px"),n.style.height="".concat(t,"px"))},on:function(e,t){h.has(e)||h.set(e,new Set),h.get(e).add(t)},off:function(e,t){var i;null===(i=h.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState:function(e,t){var i="number"!=typeof t||Number.isNaN(t)?d:Math.max(0,Math.min(1,t));c=e,d=i},getOriginalMutedState:function(){return c},getOriginalVolume:function(){return d},setAdVolume:function(e){n&&u&&(n.volume=Math.max(0,Math.min(1,e)))},getAdVolume:function(){return n&&u?n.volume:1},showPlaceholder:function(){var t;if(e.style.opacity="0",e.style.visibility="hidden",!s){var i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),s=i}s&&(s.style.display="flex",s.style.pointerEvents="auto")},hidePlaceholder:function(){s&&(s.style.display="none",s.style.pointerEvents="none"),u||(e.style.visibility="visible",e.style.opacity="1")}}}var Lu=null;function Iu(){var e,t,i,r,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="",m=!1,p=!1,y=!1;if(a.includes("Web0S")){f="LG",v="webOS",m=!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",m=!0,h="tv";var T=a.match(/Tizen\/([^\s]+)/),k=a.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=T?"Tizen ".concat(T[1]," ").concat(k).trim():"Tizen TV"}else a.includes("Philips")?(f="Philips",v="Saphi",m=!0,h="tv"):a.includes("Sharp")||a.includes("AQUOS")?(f="Sharp",v="Android TV",m=!0,h="tv"):a.includes("Android")&&(a.includes("Sony")||o.includes("Sony"))?(f="Sony",v="Android TV",m=!0,h="tv"):a.includes("Android")&&(a.includes("NetCast")||a.includes("LG"))?(f="LG",v="Android TV",m=!0,h="tv"):a.includes(" Roku")||a.includes("Roku/")?(f="Roku",v="Roku OS",m=!0,h="tv"):a.includes("AppleTV")&&(f="Apple",v="tvOS",m=!0,h="tv");if(a.includes("Android")){p=!0,v="Android",h=/Mobile/.test(a)?"mobile":"tablet",a.includes("Android")&&(0===l||a.includes("Google TV")||a.includes("XiaoMi"))&&(h="tv",m=!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")),p||m||/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===(i=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===i?void 0:i.angle),{brand:f,os:v,model:g||a.substring(0,50)+"...",deviceType:h,isSmartTV:m,isAndroid:p,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===(r=navigator.languages)||void 0===r?void 0:r.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function Ru(e){return D(this,void 0,void 0,function(){var t,i,r,n,a,s,o,l,u,c,d,h,f;return C(this,function(v){switch(v.label){case 0:if(Lu)return[2,Lu];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(),i=void 0,"undefined"!=typeof TextEncoder)i=(new TextEncoder).encode(t);else{for(r=unescape(encodeURIComponent(t)),n=new Uint8Array(r.length),u=0;u<r.length;u++)n[u]=r.charCodeAt(u);i=n}return[4,crypto.subtle.digest("SHA-256",i)];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(""),Lu=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,Lu=(d+h+f).padEnd(64,"0")]}})})}var wu="https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track";function Pu(e,t){return D(this,void 0,void 0,function(){var i,r;return C(this,function(n){switch(n.label){case 0:return i={"Content-Type":"application/json"},e&&(i.Authorization="Bearer ".concat(e)),[4,fetch(wu,{method:"POST",headers:i,body:JSON.stringify(t)})];case 1:if(!(r=n.sent()).ok)throw new Error("HTTP error! status: ".concat(r.status));return[4,r.json()];case 2:return n.sent(),[2]}})})}function Du(e){return D(this,void 0,void 0,function(){var t,i,r,n,a,s;return C(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),[4,Ru(t=Iu())];case 1:return i=o.sent(),r=w({browserId:i},t),n={"Content-Type":"application/json"},e&&(n.Authorization="Bearer ".concat(e)),[4,fetch(wu,{method:"POST",headers:n,body:JSON.stringify(r)})];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]}})})}function Cu(e,t){return D(this,void 0,void 0,function(){var i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,Ru(i=Iu())];case 1:return r=s.sent(),n=w({browserId:r},i),[4,Pu(e,w(w({},n),{licenseKey:e,adLoadedInfo:t}))];case 2:return s.sent(),[3,4];case 3:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending ad loaded tracking:",a),[3,4];case 4:return[2]}})})}function _u(e){return D(this,void 0,void 0,function(){var t,i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),[4,Ru(Iu())];case 1:return t=s.sent(),i={browserId:t,timestamp:(new Date).toISOString()},r={"Content-Type":"application/json"},e&&(r.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:r,body:JSON.stringify(i)})];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]}})})}function xu(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var r=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)&&(r[s]=a[s])}return r}),Array.from||(Array.from=function(e,t,i){var r=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var n=r.length>>>0,a=new Array(n),s=0;s<n;s++)a[s]=t?t.call(i,r[s],s):r[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 i=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){i.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,i=e.startsWith("?")?e.slice(1):e;i&&i.split("&").forEach(function(e){var i=x(e.split("="),2),r=i[0],n=i[1];if(r){var a=t.safeDecodeURIComponent(r),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 i=this.params.get(e)||[];i.push(String(t)),this.params.set(e,i)},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(i,r){i.forEach(function(i){e(i,r,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,i){t.forEach(function(t){e.push("".concat(encodeURIComponent(i),"=").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=[],i=0;i<e.length;i++){var r=e.charCodeAt(i);r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<55296||r>=57344?t.push(224|r>>12,128|r>>6&63,128|63&r):(i++,r=65536+((1023&r)<<10|1023&e.charCodeAt(i)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}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(i){return t.resolve(e()).then(function(){return i})},function(i){return t.resolve(e()).then(function(){throw i})})})}function Mu(){var e,t,i,r=navigator.userAgent,n=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"}(),a="Unknown",s="0",o=0,l=!1,u=!1,c=!0,d=!0,h="ima",f=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(r),v=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(r);if(i=f>0?f:void 0,/Web0S|webOS|LG Browser|LGSTB/i.test(r)){if(a="LG WebOS",l=!0,(g=r.match(/Web0S[/\s]*([\d.]+)/i)||r.match(/webOS[/\s]*([\d.]+)/i))&&g[1]||(g=r.match(/webOSTV[/\s-]*([\d.]+)/i)||r.match(/webOS\.TV[/\s-]*([\d.]+)/i)),g&&g[1])e=o=(m=(s=g[1]).split("."))[0]?parseInt(m[0],10):0;else f>0?f>=79?(e=6,s="6.0",o=6):f>=68?(e=5,s="5.0",o=5):f>=53?(e=4,s="4.0",o=4):f>=38?(e=3,s="3.0",o=3):(e=2,s="2.0",o=2):(s="Unknown",e=void 0);void 0!==e&&e>=4||f>=53?(c=!0,h="ima",u=!1):(c=!1,h="hls",u=!0)}else if(/Tizen/i.test(r)){var g,m;if(a="Samsung Tizen",l=!0,"Unknown"!==(s=(g=r.match(/Tizen[/\s]*([\d.]+)/i))&&g[1]?g[1]:"Unknown"))t=o=(m=s.split("."))[0]?parseInt(m[0],10):0;void 0!==t&&t>=4||void 0!==t&&t>=3&&f>=47||f>=53?(c=!0,h="ima",u=!1):(c=!1,h="hls",u=!0)}else/SMART-TV|SmartTV/i.test(r)?(a="Smart TV",l=!0,f>=53?(c=!0,h="ima"):(c=!1,h="hls",u=!0)):/NetCast/i.test(r)?(a="LG NetCast",l=!0,u=!0,c=!1,h="hls"):/BRAVIA/i.test(r)?(a="Sony BRAVIA",l=!0,f>=53?(c=!0,h="ima"):(c=!1,h="hls",u=!0)):(f>0&&(a="Chrome",s=f.toString(),o=f,f<50&&(c=!1,d=!1,h="hls")),v>0&&v<600&&(d=!1,f<50&&(c=!1,h="hls")));return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(d=!1,c=!1,h="hls"),"undefined"==typeof URLSearchParams&&(d=!1),{name:a,version:s,majorVersion:o,isSmartTV:l,isLegacyTV:u,platform:n,supportsIMA:c,supportsModernJS:d,recommendedAdPlayer:h,webOSVersion:e,tizenVersion:t,chromeVersion:i}}function Ou(){var e=Mu();if(e.isLegacyTV)return!1;if("undefined"==typeof document||"function"!=typeof document.createElement)return!1;try{if(!document.createElement("video"))return!1}catch(e){return!1}return"undefined"!=typeof Promise&&e.supportsIMA}function Fu(e){if(void 0===e&&(e=!1),e){var t=Mu(),i=Ou();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",w(w(w(w({browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsIMA:i,supportsModernJS:t.supportsModernJS,recommendedAdPlayer:t.recommendedAdPlayer},void 0!==t.webOSVersion?{webOSVersion:t.webOSVersion}:{}),void 0!==t.tizenVersion?{tizenVersion:t.tizenVersion}:{}),void 0!==t.chromeVersion?{chromeVersion:t.chromeVersion}:{}),{userAgent:navigator.userAgent}))}}function Nu(){var e={};return Mu().isSmartTV&&(e.allowNativeHls=!0),e}var Bu=function(){function e(e){this.pendingNextAdBids=null,this.continuousFetchLoopPromise=null,this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.adPodQueue=[],this.lastHeartbeatTime=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.showAds=!1,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.activeAdRequestToken=null,this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.continuousFetchingActive=!1,this.isInAdTransition=!1,this.maxPlaceholderDurationMs=5e3,this.isShowingPlaceholder=!1,this.totalAdRequestsInBreak=0,this.maxTotalAdRequestsPerBreak=20,this.pendingAdBreak=null,this.savedMutedStateBeforeScte=null,this.consecutiveFailures=0,this.maxConsecutiveFailures=5,this.lastAdRequestTime=0,this.minAdRequestIntervalMs=2500,this.backoffBaseMs=1e3,this.maxBackoffMs=15e3,this.adTransitionGapMs=1500,xu();var t=Nu();this.config=w(w({},t),e),this.video=e.videoElement,Fu(e.debugAdTiming),this.prebidManager=Eu(void 0!==e.debugAdTiming?{debug:!!e.debugAdTiming}:{}),this.adLayer=bu(this.video,{continueLiveStreamDuringAds:!1,debug:!!e.debugAdTiming})}return e.prototype.adRequest=function(){return D(this,void 0,void 0,function(){return C(this,function(e){switch(e.label){case 0:return[4,this.prebidManager.initialize()];case 1:return e.sent(),[2,this.prebidManager.requestBidsUntilResponse()]}})})},e.prototype.load=function(){return D(this,void 0,void 0,function(){var e,t,i=this;return C(this,function(r){switch(r.label){case 0:return this.attached||this.attach(),this.initializeTracking(),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 - VOD mode:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:"vod (main video pauses during ads)"}),this.adLayer.updateOptions({continueLiveStreamDuringAds:!1,mainHlsInstance:null}),this.config.autoplay?[4,null===(t=this.video.play())||void 0===t?void 0:t.catch(function(){})]:[3,2]):[3,3];case 1:r.sent(),r.label=2;case 2:return[2];case 3:return this.hls=new pu(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(pu.Events.MEDIA_ATTACHED,function(){var e;null===(e=i.hls)||void 0===e||e.loadSource(i.config.src)}),this.hls.on(pu.Events.MANIFEST_PARSED,function(e,t){return D(i,void 0,void 0,function(){var e,t,i,r,n,a,s,o;return C(this,function(l){switch(l.label){case 0:return!1===this.config.allowNativeHls?this.isLiveStream=!0:this.isLiveStream=null!==(n=null===(r=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===r?void 0:r.some(function(e){var t,i;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(i=null==e?void 0:e.details)||void 0===i?void 0:i.type)}))&&void 0!==n&&n,this.config.debugAdTiming&&(e=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})),this.adLayer.updateOptions({continueLiveStreamDuringAds:this.shouldContinueLiveStreamDuringAds(),mainHlsInstance:null!==(a=this.hls)&&void 0!==a?a:null}),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,t=null!==(s=this.config.minSegmentsBeforePlay)&&void 0!==s?s:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",t,"segments to buffer before playback"),0!==t&&this.config.autoplay?[3,2]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(o=this.video.play())||void 0===o?void 0:o.catch(function(){})]:[3,2]);case 1:l.sent(),l.label=2;case 2:return[2]}})})}),this.hls.on(pu.Events.LEVEL_LOADED,function(e,t){var r,n,a,s;if(!i.inAdBreak&&!i.pendingAdBreak){var o=null==t?void 0:t.details;if(o&&o.fragments&&0!==o.fragments.length)for(var l=Math.min(5,o.fragments.length),u=0;u<l;u++){var c=o.fragments[u],d=null==c?void 0:c.tagList;if(Array.isArray(d))try{for(var h=(r=void 0,_(d)),f=h.next();!f.done;f=h.next()){var v=f.value,g="",m="";if(Array.isArray(v))g=String(null!==(a=v[0])&&void 0!==a?a:""),m=String(null!==(s=v[1])&&void 0!==s?s:"");else if("string"==typeof v){var p=v.indexOf(":");p>=0?(g=v.substring(0,p),m=v.substring(p+1)):g=v}if(g&&(g.includes("EXT-X-CUE-OUT")||g.includes("EXT-X-DATERANGE"))){var y=g.includes("EXT-X-DATERANGE")?i.parseAttributeList(m):{};if(g.includes("EXT-X-CUE-OUT")||"SCTE35-OUT"in y||void 0!==y["SCTE35-OUT"]){var E=i.parseCueOutDuration(m),T=w(w({type:"start"},void 0!==E?{durationSeconds:E}:{}),{raw:{tag:g,value:m,earlyDetection:!0}});return i.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] 🎯 EARLY SCTE-35 DETECTION: Ad break marker found in fragment",u,"- starting pre-fetch (NOT playing yet)"),void i.startAdPrefetch(T,null==c?void 0:c.sn)}}}}catch(e){r={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(r)throw r.error}}}}}),this.hls.on(pu.Events.FRAG_BUFFERED,function(e,t){return D(i,void 0,void 0,function(){var e,t,i,r=this;return C(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.inAdBreak||this.adLayer.isAdPlaying()?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Ad break active — deferring play() to handleAdPodComplete().")),[3,3]):[3,1]:[3,3]):[3,3]);case 1:return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Starting playback.")),[4,null===(i=this.video.play())||void 0===i?void 0:i.catch(function(e){r.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})];case 2:n.sent(),n.label=3;case 3:return[2]}})})}),this.hls.on(pu.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 i.onId3Tag(e)})}),this.hls.on(pu.Events.FRAG_CHANGED,function(e,t){var r,n,a,s,o,l=null==t?void 0:t.frag,u=null==l?void 0:l.tagList;if(Array.isArray(u))try{for(var c=_(u),d=c.next();!d.done;d=c.next()){var h=d.value,f="",v="";if(Array.isArray(h))f=String(null!==(a=h[0])&&void 0!==a?a:""),v=String(null!==(s=h[1])&&void 0!==s?s:"");else if("string"==typeof h){var g=h.indexOf(":");g>=0?(f=h.substring(0,g),v=h.substring(g+1)):(f=h,v="")}if(f)if(f.includes("EXT-X-CUE-OUT-CONT")){var m=i.parseCueOutCont(v),p=w(w(w({type:"progress"},void 0!==(null==m?void 0:m.duration)?{durationSeconds:m.duration}:{}),void 0!==(null==m?void 0:m.elapsed)?{ptsSeconds:m.elapsed}:{}),{raw:{tag:f,value:v}});i.onScte35Marker(p)}else if(f.includes("EXT-X-CUE-OUT")){var y=i.parseCueOutDuration(v);p=w(w({type:"start"},void 0!==y?{durationSeconds:y}:{}),{raw:{tag:f,value:v}});i.onScte35Marker(p)}else if(f.includes("EXT-X-CUE-IN"))i.onScte35Marker({type:"end",raw:{tag:f,value:v}});else if(f.includes("EXT-X-DATERANGE")){var E=i.parseAttributeList(v),T="SCTE35-OUT"in E||void 0!==E["SCTE35-OUT"],k="SCTE35-IN"in E||void 0!==E["SCTE35-IN"],S=String(null!==(o=E.CLASS)&&void 0!==o?o:""),A=i.toNumber(E.DURATION);if(T||/com\.apple\.hls\.cue/i.test(S)){p=w(w({type:"start"},void 0!==A?{durationSeconds:A}:{}),{raw:{tag:f,value:v,attrs:E}});i.onScte35Marker(p)}k&&i.onScte35Marker({type:"end",raw:{tag:f,value:v,attrs:E}})}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(r)throw r.error}}}),this.hls.on(pu.Events.ERROR,function(e,t){var r,n;if(null==t?void 0:t.fatal)switch(t.type){case pu.ErrorTypes.NETWORK_ERROR:null===(r=i.hls)||void 0===r||r.startLoad();break;case pu.ErrorTypes.MEDIA_ERROR:null===(n=i.hls)||void 0===n||n.recoverMediaError();break;default:i.destroy()}}),this.hls.attachMedia(this.video),[2]}})})},e.prototype.getAdSource=function(){return"prebid"},e.prototype.attachAdLayerEventListeners=function(){var e=this;this.adLayer.on("ad_impression",function(){e.config.licenseKey&&function(e,t){D(this,void 0,void 0,function(){var i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,Ru(i=Iu())];case 1:return r=s.sent(),n=w({browserId:r},i),[4,Pu(e,w(w({},n),{licenseKey:e,adImpressionInfo:t}))];case 2:return s.sent(),[3,4];case 3:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending ad impression tracking:",a),[3,4];case 4:return[2]}})})}(e.config.licenseKey,{source:e.getAdSource(),adIndex:e.currentAdIndex,timestamp:(new Date).toISOString()})}),this.adLayer.on("ad_error",function(t){var i="Ad playback failed";if(t){var r=t.code||t.errorCode||"unknown",n=t.vastErrorCode,a=t.message||t.errorMessage||"Unknown error",s=t.cause||t.innerError||t.error;if(i="Ad error: AdError ".concat(r,": ").concat(a),n&&"N/A"!==n&&n!==r&&(i+=" (VAST Error Code: ".concat(n,")")),s){var o="string"==typeof s?s:s.message||String(s);i+=". Caused by: ".concat(o)}}console.error("[AD-ERROR]",i,t||""),e.adLayer.stop().catch(function(){}),e.handleAdFailure()}),this.adLayer.on("content_pause",function(){e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!0,e.inAdBreak&&null!=e.expectedAdBreakDurationMs&&null==e.adStopTimerId&&(e.scheduleAdStopCountdown(e.getRemainingAdMs()),e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)")),e.adLayer.setAdVolume(e.adLayer.getOriginalMutedState()?1:e.adLayer.getOriginalVolume()),e.isShowingPlaceholder&&(e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Hiding placeholder - new ads starting"),e.hidePlaceholderLayer(),e.adLayer.hidePlaceholder(),e.isShowingPlaceholder=!1)}),this.adLayer.on("content_resume",function(){var t=e.getRemainingAdMs();if(e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] content_resume received, inAdBreak=%s, remaining=%s, pendingNext=%s",e.inAdBreak,t,!!e.pendingNextAdBids),e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!1,!e.inAdBreak)return e.video.style.visibility="visible",e.video.style.opacity="1",void e.syncMainContentAudioWhenVisible();if(e.consecutiveFailures=0,e.pendingNextAdBids&&e.pendingNextAdBids.length>0){var i=M([],x(e.pendingNextAdBids),!1);return e.pendingNextAdBids=null,e.video.muted||(e.video.muted=!0,e.video.volume=0),e.showPlaceholderLayer(),e.adLayer.showPlaceholder(),e.isInAdTransition=!0,void setTimeout(function(){var t;if(e.isInAdTransition=!1,e.inAdBreak&&0!==i.length){var r=null!==(t=e.pendingNextAdBids)&&void 0!==t?t:i;e.pendingNextAdBids=null,e.currentAdIndex++,e.adLayer.playAd(r).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] playAd(pending) failed:",t),e.handleAdFailure()})}},e.adTransitionGapMs)}e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] content_resume: no more ads, ending ad pod and restoring main content sound"),e.handleAdPodComplete()})},e.prototype.ensureFillerVideo=function(){if(!this.fillerVideo&&this.video.parentElement){var e=document.createElement("video");e.src="https://f000.backblazeb2.com/file/AdStormAds/384/Sonifi_Filler.mp4",e.loop=!0,e.muted=!1,e.playsInline=!0,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="cover",e.style.zIndex="20",e.style.display="none",e.preload="auto",this.video.parentElement.appendChild(e),this.fillerVideo=e}},e.prototype.showPlaceholderLayer=function(){var e=this;this.ensureFillerVideo(),this.fillerVideo&&(this.video.muted||(this.video.muted=!0,this.video.volume=0),this.fillerVideo.style.display="block",this.fillerVideo.play().catch(function(){e.fillerVideo&&(e.fillerVideo.style.display="none")}),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Showing filler video layer"))},e.prototype.hidePlaceholderLayer=function(){this.fillerVideo&&(this.fillerVideo.style.display="none",this.fillerVideo.pause(),this.fillerVideo.currentTime=0,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Hiding filler video layer"))},e.prototype.startFillerBreakTimer=function(e){var t=this;this.stopFillerBreakTimer(),this.showPlaceholderLayer(),this.fillerBreakTimerId=setTimeout(function(){t.fillerBreakTimerId=void 0,t.hidePlaceholderLayer(),t.inAdBreak&&t.handleAdPodComplete()},e)},e.prototype.stopFillerBreakTimer=function(){void 0!==this.fillerBreakTimerId&&(clearTimeout(this.fillerBreakTimerId),this.fillerBreakTimerId=void 0)},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.adLayer.initialize(),this.ensureFillerVideo(),this.adLayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.attachAdLayerEventListeners(),this.timeUpdateHandler=function(){e.onTimeUpdate(e.video.currentTime)},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.nativeHlsMode&&e.videoSrcProtection&&!e.adLayer.isAdPlaying()){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",e.videoSrcProtection);var t=e.video.currentTime,i=e.video.paused;e.video.src=e.videoSrcProtection,e.video.currentTime=t,i||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,i,r,n,a=this.decodeId3ValueToText(e.value);if(a){var s=a.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||a.match(/CUE-OUT(?::([^\r\n]*))?/i);if(s){var o=(null!==(t=s[1])&&void 0!==t?t:"").trim(),l=this.parseCueOutDuration(o);return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==l?{durationSeconds:l}:{}),{raw:{id3:a}})}var u=a.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(u){o=(null!==(i=u[1])&&void 0!==i?i:"").trim();var c=this.parseCueOutCont(o);return w(w(w({type:"progress"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==(null==c?void 0:c.duration)?{durationSeconds:c.duration}:{}),{raw:{id3:a}})}if(a.match(/EXT-X-CUE-IN\b/i)||a.match(/CUE-IN\b/i))return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});var d=a.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(d){var h=this.parseAttributeList(null!==(r=d[1])&&void 0!==r?r:""),f="SCTE35-OUT"in h||void 0!==h["SCTE35-OUT"],v="SCTE35-IN"in h||void 0!==h["SCTE35-IN"],g=String(null!==(n=h.CLASS)&&void 0!==n?n:""),m=this.toNumber(h.DURATION);if(f||/com\.apple\.hls\.cue/i.test(g))return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==m?{durationSeconds:m}:{}),{raw:{id3:a,attrs:h}});if(v)return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a,attrs:h}})}if(/SCTE35-OUT/i.test(a))return w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(/SCTE35-IN/i.test(a))return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(e.value instanceof Uint8Array){var p=this.parseScte35Binary(e.value);if(p)return p}}},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 i="",r=0;r<e.length;r++)i+=String.fromCharCode(e[r]);return i}catch(e){return}},e.prototype.onScte35Marker=function(e){var t,i,r,n,a=this;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime,raw:e.raw,hasPendingAdBreak:!!this.pendingAdBreak}),"start"!==e.type){if("progress"===e.type&&this.inAdBreak){if(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs){var s=Date.now()-this.currentAdBreakStartWallClockMs,o=Math.max(0,this.expectedAdBreakDurationMs-s);this.scheduleAdStopCountdown(o)}if(!this.adLayer.isAdPlaying()&&null!=this.pendingNextAdBids&&this.pendingNextAdBids.length>0){var l=this.pendingNextAdBids;this.pendingNextAdBids=null,this.currentAdIndex++,this.adLayer.playAd(l).catch(function(){return a.handleAdFailure()})}}else if("end"===e.type){var u=this.getRemainingAdMs(),c=this.adLayer.isAdPlaying(),d=null!=this.pendingNextAdBids&&this.pendingNextAdBids.length>0;return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 end marker received:",{inAdBreak:this.inAdBreak,remaining:u,adPlaying:c,hasQueuedAds:d,activeAdRequest:null!==this.activeAdRequestToken}),this.inAdBreak?c||u>500?void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ignoring premature SCTE-35 end marker - ads still active or time remaining")):(this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),c&&this.adLayer.stop().catch(function(){}),void this.handleAdPodComplete()):void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ignoring SCTE-35 end marker - not in ad break"))}}else{if(null==this.savedMutedStateBeforeScte&&(this.savedMutedStateBeforeScte={muted:this.video.muted,volume:this.video.volume},this.adLayer.updateOriginalMutedState(this.video.muted,this.video.volume)),this.video.muted||(this.video.muted=!0,this.video.volume=0,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted video on SCTE start marker")),this.inAdBreak)return void(null==this.expectedAdBreakDurationMs&&null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Updated ad break duration from subsequent marker: ".concat(this.expectedAdBreakDurationMs,"ms")),this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)));this.inAdBreak=!0;var h=null!=e.durationSeconds?1e3*e.durationSeconds:null!=(null===(t=this.pendingAdBreak)||void 0===t?void 0:t.marker.durationSeconds)?1e3*this.pendingAdBreak.marker.durationSeconds:void 0;if(this.expectedAdBreakDurationMs=h,this.currentAdBreakStartWallClockMs=Date.now(),this.config.licenseKey){var f=w(w(w({source:"scte35",timestamp:(new Date).toISOString()},null!=e.durationSeconds&&{durationSeconds:e.durationSeconds}),null!=e.ptsSeconds&&{ptsSeconds:e.ptsSeconds}),null!=(null===(i=this.pendingAdBreak)||void 0===i?void 0:i.detectedAtFragmentSn)&&{detectedAtFragmentSn:this.pendingAdBreak.detectedAtFragmentSn});!function(e,t){D(this,void 0,void 0,function(){var i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,Ru(i=Iu())];case 1:return r=s.sent(),n=w({browserId:r},i),[4,Pu(e,w(w({},n),{licenseKey:e,adDetectInfo:t}))];case 2:return s.sent(),[3,4];case 3:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending ad detect tracking:",a),[3,4];case 4:return[2]}})})}(this.config.licenseKey,f)}var v=this.isManifestBasedMarker(e),g=null===(r=this.config.immediateManifestAds)||void 0===r||r;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:v,forceImmediate:g,hasPts:"number"==typeof e.ptsSeconds}),v&&g)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)"),this.clearAdStartTimer(),this.handleAdStart(e);else if("number"==typeof e.ptsSeconds){var m=null!==(n=this.config.driftToleranceMs)&&void 0!==n?n:1e3,p=1e3*this.video.currentTime,y=p-this.ptsDriftEmaMs,E=Math.floor(1e3*e.ptsSeconds-y);this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:p,estCurrentPtsMs:y,markerPtsMs:1e3*e.ptsSeconds,deltaMs:E,tolerance:m}),E>m?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Scheduling ad start in ".concat(E,"ms")),this.scheduleAdStartIn(E)):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.clearAdStartTimer(),this.handleAdStart(e))}else this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.clearAdStartTimer(),this.handleAdStart(e);null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)}},e.prototype.parseCueOutDuration=function(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var i=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(i&&null!=i[1]){var r=i[1],n=parseFloat(r);return Number.isNaN(n)?void 0:n}},e.prototype.parseCueOutCont=function(e){var t={},i=e.match(/Elapsed\s*=\s*([0-9.]+)/i),r=e.match(/Duration\s*=\s*([0-9.]+)/i);if(i&&null!=i[1]){var n=parseFloat(i[1]);Number.isNaN(n)||(t.elapsed=n)}if(r&&null!=r[1]){var a=parseFloat(r[1]);Number.isNaN(a)||(t.duration=a)}if(!("elapsed"in t)||!("duration"in t)){var s=e.match(/([0-9.]+)\s*\/\s*([0-9.]+)/);if(s&&s[1]&&s[2]){var o=parseFloat(s[1]),l=parseFloat(s[2]);Number.isNaN(o)||"elapsed"in t||(t.elapsed=o),Number.isNaN(l)||"duration"in t||(t.duration=l)}}if("elapsed"in t||"duration"in t)return t},e.prototype.parseAttributeList=function(e){for(var t,i,r,n,a={},s=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(n=s.exec(e));){var o=null!==(t=n[1])&&void 0!==t?t:"",l=null!==(r=null!==(i=n[3])&&void 0!==i?i:n[4])&&void 0!==r?r:"";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.isManifestBasedMarker=function(e){var t=e.raw;if(!t)return!1;if(t.tag){var i=String(t.tag);return i.includes("EXT-X-CUE-OUT")||i.includes("EXT-X-CUE-IN")||i.includes("EXT-X-DATERANGE")}return t.id3||t.splice_command_type,!1},e.prototype.parseScte35Binary=function(e){var t=new(function(){function e(e){this.buf=e,this.bytePos=0,this.bitPos=0}return e.prototype.readBits=function(e){for(var t=0;e>0;){if(this.bytePos>=this.buf.length)return t;var i=8-this.bitPos,r=Math.min(e,i);t=t<<r|this.buf[this.bytePos]>>i-r&((1<<r)-1&255),this.bitPos+=r,this.bitPos>=8&&(this.bitPos=0,this.bytePos+=1),e-=r}return t>>>0},e.prototype.skipBits=function(e){this.readBits(e)},e}())(e);if(252===t.readBits(8)){t.readBits(1),t.readBits(1),t.readBits(2);t.readBits(12);t.readBits(8),t.readBits(1),t.readBits(6);t.readBits(1),t.readBits(32);t.readBits(8),t.readBits(12);t.readBits(12);if(5===t.readBits(8)){t.readBits(32);var i=1===t.readBits(1);if(t.readBits(7),!i){var r=1===t.readBits(1),n=1===t.readBits(1),a=1===t.readBits(1),s=1===t.readBits(1);if(t.readBits(4),n&&!s)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7);else if(!n)for(var o=t.readBits(8),l=0;l<o;l++){if(t.readBits(8),!s)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}var u=void 0;if(a)t.readBits(6),t.readBits(1),u=(4294967296*t.readBits(1)+t.readBits(32))/9e4;if(t.readBits(16),t.readBits(8),t.readBits(8),r)return w(w({type:"start"},void 0!==u?{durationSeconds:u}:{}),{raw:{splice_command_type:5}})}}}},e.prototype.initializeTracking=function(){var e=this;Du(this.config.licenseKey).then(function(){e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)}).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send initial tracking:",t),e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)})},e.prototype.sendHeartbeatIfNeeded=function(){var e=this,t=Date.now();(!this.lastHeartbeatTime||t-this.lastHeartbeatTime>3e4)&&(this.lastHeartbeatTime=t,_u(this.config.licenseKey).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",t)}))},e.prototype.getCurrentAdIndex=function(){return this.currentAdIndex},e.prototype.getTotalAdsInBreak=function(){return this.totalAdsInBreak},e.prototype.isAdPlaying=function(){return this.inAdBreak&&this.adLayer.isAdPlaying()},e.prototype.isShowingAds=function(){return this.showAds},e.prototype.syncMainContentAudioWhenVisible=function(){if(!(this.showAds||this.adLayer.isAdPlaying())){var e=this.adLayer.getOriginalMutedState(),t=this.adLayer.getOriginalVolume();this.video.muted!==e&&(this.video.muted=e),Math.abs(this.video.volume-t)>.01&&(this.video.volume=t)}},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.shouldContinueLiveStreamDuringAds=function(){return!this.config.allowNativeHls&&!!this.isLiveStream},e.prototype.startAdPrefetch=function(e,t){var i=this;this.pendingAdBreak||this.inAdBreak||(this.pendingAdBreak=w(w({marker:e},void 0!==t?{detectedAtFragmentSn:t}:{}),{isFetching:!1,fetchStartTime:Date.now()}),this.adRequest().then(function(){}).catch(function(){i.config.debugAdTiming&&console.log("[PREFETCH] Prebid auction prefetch failed, will request at playback time")}),this.config.debugAdTiming&&console.log("[PREFETCH] Ad break marker registered, auction prefetch started"))},e.prototype.clearPendingAdBreak=function(){null!=this.prefetchTimerId&&(clearTimeout(this.prefetchTimerId),this.prefetchTimerId=void 0),this.pendingAdBreak=null},e.prototype.startContinuousFetchLoop=function(){null==this.continuousFetchLoopPromise&&(this.continuousFetchLoopPromise=this.runContinuousFetchLoop())},e.prototype.runContinuousFetchLoop=function(){return D(this,void 0,void 0,function(){var e,t,i,r=this;return C(this,function(n){switch(n.label){case 0:e=function(){var e=Math.pow(2,r.consecutiveFailures);return Math.min(r.backoffBaseMs*e,r.maxBackoffMs)},t=function(){var t,r,n,a;return C(this,function(s){switch(s.label){case 0:return i.consecutiveFailures>=i.maxConsecutiveFailures||i.totalAdRequestsInBreak>=i.maxTotalAdRequestsPerBreak?[2,"break"]:(t=i.lastAdRequestTime?i.minAdRequestIntervalMs+(i.consecutiveFailures>0?e():0):0,(r=Date.now()-i.lastAdRequestTime)<t&&i.lastAdRequestTime>0?[4,new Promise(function(e){return setTimeout(e,t-r)})]:[3,2]);case 1:s.sent(),s.label=2;case 2:if(!i.inAdBreak||!i.continuousFetchingActive)return[2,"break"];s.label=3;case 3:return s.trys.push([3,10,,11]),[4,i.adRequest()];case 4:return n=s.sent(),i.lastAdRequestTime=Date.now(),i.inAdBreak?n.length>0?(i.consecutiveFailures=0,i.adLayer.isAdPlaying()||i.isInAdTransition?(i.pendingNextAdBids=n,i.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] Next ad response stored (ad currently playing or in transition)"),[3,7]):[3,5]):[3,8]:[2,"break"];case 5:return i.currentAdIndex++,i.config.licenseKey&&Cu(i.config.licenseKey,{source:i.getAdSource(),timestamp:(new Date).toISOString()}),[4,i.adLayer.playAd(n)];case 6:s.sent(),null!=i.expectedAdBreakDurationMs&&null==i.adStopTimerId&&i.scheduleAdStopCountdown(i.getRemainingAdMs()),i.adLayer.setAdVolume(i.adLayer.getOriginalMutedState()?1:i.adLayer.getOriginalVolume()),s.label=7;case 7:return[3,9];case 8:i.consecutiveFailures++,s.label=9;case 9:return[3,11];case 10:return a=s.sent(),i.consecutiveFailures++,i.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] adRequest failed:",a),[3,11];case 11:return[4,new Promise(function(t){return setTimeout(t,e())})];case 12:return s.sent(),[2]}})},i=this,n.label=1;case 1:return this.inAdBreak&&this.continuousFetchingActive?[5,t()]:[3,3];case 2:return"break"===n.sent()?[3,3]:[3,1];case 3:return this.continuousFetchLoopPromise=null,[2]}})})},e.prototype.handleAdStart=function(e){return D(this,void 0,void 0,function(){var t,i,r,n,a,s,o,l;return C(this,function(u){switch(u.label){case 0:t=null!=e.durationSeconds?1e3*e.durationSeconds:void 0,this.config.debugAdTiming&&(i=this.isLiveStream?"LIVE":"VOD",console.log("[CONTINUOUS-FETCH] 📺 ".concat(i," MODE: Target duration=").concat(t,"ms"))),this.consecutiveFailures=0,this.continuousFetchingActive=!0,this.continuousFetchLoopPromise=null,this.pendingNextAdBids=null,this.isShowingPlaceholder=!1,this.totalAdRequestsInBreak=0,null!=this.savedMutedStateBeforeScte||this.video.muted||(this.savedMutedStateBeforeScte={muted:!1,volume:this.video.volume}),r=null!==(l=this.savedMutedStateBeforeScte)&&void 0!==l?l:{muted:this.video.muted,volume:this.video.volume},this.adLayer.updateOriginalMutedState(r.muted,r.volume),this.video.muted||(this.video.muted=!0,this.video.volume=0,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted video in handleAdStart")),this.inAdBreak=!0,this.currentAdBreakStartWallClockMs=Date.now(),this.currentAdIndex=0,this.totalAdsInBreak=1,this.adPodQueue=[],this.showAds=!0,null!=t?this.startFillerBreakTimer(t):this.showPlaceholderLayer(),this.adLayer.showPlaceholder(),null==this.expectedAdBreakDurationMs&&null!=t&&(this.expectedAdBreakDurationMs=t),this.clearPendingAdBreak(),n=Date.now(),this.activeAdRequestToken=n,this.startAdFailsafeTimer(n),this.startAdRequestWatchdog(n),u.label=1;case 1:return u.trys.push([1,7,,9]),this.lastAdRequestTime=Date.now(),[4,this.adRequest()];case 2:return a=u.sent(),this.inAdBreak?a.length>0?(this.consecutiveFailures=0,this.config.licenseKey&&Cu(this.config.licenseKey,{source:this.getAdSource(),timestamp:(new Date).toISOString()}),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ First ad request successful, starting playback"),this.currentAdIndex++,[4,this.adLayer.playAd(a)]):[3,4]:[2];case 3:return u.sent(),null!=this.expectedAdBreakDurationMs&&null==this.adStopTimerId&&this.scheduleAdStopCountdown(this.getRemainingAdMs()),s=r.muted?1:r.volume,this.adLayer.setAdVolume(s),[3,6];case 4:return this.consecutiveFailures++,[4,this.showPlaceholderAndWaitForAds()];case 5:u.sent(),u.label=6;case 6:return[3,9];case 7:return o=u.sent(),this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ First ad request failed:",o),this.consecutiveFailures++,[4,this.showPlaceholderAndWaitForAds()];case 8:return u.sent(),[3,9];case 9:return this.startContinuousFetchLoop(),[2]}})})},e.prototype.stopContinuousFetching=function(){this.continuousFetchingActive=!1,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching")},e.prototype.tryNextAvailableAdWithRateLimit=function(){return D(this,void 0,void 0,function(){var e,t,i,r,n;return C(this,function(a){switch(a.label){case 0:return this.consecutiveFailures>=this.maxConsecutiveFailures?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (".concat(this.consecutiveFailures,"), ending ad break gracefully")),this.handleAdPodComplete(),[2]):(e=Math.pow(2,this.consecutiveFailures),t=Math.min(this.backoffBaseMs*e,this.maxBackoffMs),i=this.minAdRequestIntervalMs+(this.consecutiveFailures>0?t:0),(r=Date.now()-this.lastAdRequestTime)<i?(n=i-r,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏳ Rate limiting: waiting ".concat(n,"ms before next request (backoff: ").concat(this.consecutiveFailures," failures)")),[4,new Promise(function(e){return setTimeout(e,n)})]):[3,2]);case 1:a.sent(),a.label=2;case 2:return[2,this.tryNextAvailableAd(0)]}})})},e.prototype.tryNextAvailableAd=function(){return D(this,arguments,void 0,function(e){var t,i;return void 0===e&&(e=0),C(this,function(e){switch(e.label){case 0:if(this.totalAdRequestsInBreak>=this.maxTotalAdRequestsPerBreak)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Max ad requests per break (".concat(this.maxTotalAdRequestsPerBreak,") reached")),this.handleAdPodComplete(),[2];if(this.getRemainingAdMs()<=500&&null!=this.expectedAdBreakDurationMs)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break"),this.handleAdPodComplete(),[2];if(this.consecutiveFailures>=this.maxConsecutiveFailures)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (".concat(this.consecutiveFailures,"), ending ad break")),this.handleAdPodComplete(),[2];e.label=1;case 1:return e.trys.push([1,9,,11]),this.lastAdRequestTime=Date.now(),[4,this.adRequest()];case 2:return t=e.sent(),this.inAdBreak?t.length>0?(this.consecutiveFailures=0,this.currentAdIndex++,this.totalAdRequestsInBreak++,this.adLayer.isAdPlaying()||this.isInAdTransition?(this.pendingNextAdBids=t,[3,5]):[3,3]):[3,6]:[2];case 3:return this.config.licenseKey&&Cu(this.config.licenseKey,{source:this.getAdSource(),timestamp:(new Date).toISOString()}),[4,this.adLayer.playAd(t)];case 4:e.sent(),null!=this.expectedAdBreakDurationMs&&null==this.adStopTimerId&&this.scheduleAdStopCountdown(this.getRemainingAdMs()),this.adLayer.setAdVolume(this.adLayer.getOriginalMutedState()?1:this.adLayer.getOriginalVolume()),e.label=5;case 5:return[3,8];case 6:return this.consecutiveFailures++,[4,this.showPlaceholderAndWaitForAds()];case 7:e.sent(),e.label=8;case 8:return[3,11];case 9:return i=e.sent(),this.consecutiveFailures++,this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] tryNextAvailableAd request failed:",i),[4,this.showPlaceholderAndWaitForAds()];case 10:return e.sent(),[3,11];case 11:return[2]}})})},e.prototype.showPlaceholderAndWaitForAds=function(){return D(this,void 0,void 0,function(){var e,t,i,r,n,a,s;return C(this,function(o){switch(o.label){case 0:if(e=this.getRemainingAdMs(),t=Math.min(this.maxPlaceholderDurationMs,e),this.consecutiveFailures>=this.maxConsecutiveFailures)return this.getRemainingAdMs()>=1e3?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Max failures reached but break still active — resetting and continuing filler"),this.consecutiveFailures=0,[2]):(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Skipping placeholder - too many consecutive failures"),this.handleAdPodComplete(),[2]);if(t<1e3)return this.handleAdPodComplete(),[2];this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⬛ Showing placeholder for ".concat(t,"ms while waiting for ad response")),this.isShowingPlaceholder=!0,this.showPlaceholderLayer(),this.adLayer.showPlaceholder(),i=300,r=Math.floor(t/i),n=0,o.label=1;case 1:return n<r?[4,new Promise(function(e){return setTimeout(e,i)})]:[3,10];case 2:if(o.sent(),!this.inAdBreak)return[2];if(this.consecutiveFailures>=this.maxConsecutiveFailures)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Too many failures during placeholder wait — resetting and continuing filler"),this.consecutiveFailures=0,[3,10];if(!(null!=this.pendingNextAdBids&&this.pendingNextAdBids.length>0))return[3,8];a=this.pendingNextAdBids,this.pendingNextAdBids=null,this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),this.currentAdIndex++,o.label=3;case 3:return o.trys.push([3,5,,7]),[4,this.adLayer.playAd(a)];case 4:return o.sent(),this.consecutiveFailures=0,[3,7];case 5:return o.sent(),this.consecutiveFailures++,[4,this.tryNextAvailableAdWithRateLimit()];case 6:return o.sent(),[3,7];case 7:return[2];case 8:if(this.adLayer.isAdPlaying())return this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),[2];o.label=9;case 9:return n++,[3,1];case 10:return(s=this.getRemainingAdMs())>=1e3?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder slot expired, ".concat(s,"ms still remaining — continuing filler")),this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),this.consecutiveFailures=0,[2]):(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder timeout, ending ad break"),this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),this.handleAdPodComplete(),[2])}})})},e.prototype.onTimeUpdate=function(e){this.adLayer.isAdPlaying()},e.prototype.scheduleAdStopCountdown=function(e){var t=this;this.clearAdStopTimer();var i=Math.max(0,Math.floor(e));0!==i?this.adStopTimerId=window.setTimeout(function(){t.ensureAdStoppedByTimer()},i):this.ensureAdStoppedByTimer()},e.prototype.clearAdStopTimer=function(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)},e.prototype.ensureAdStoppedByTimer=function(){var e,t;if(this.inAdBreak){this.adStopTimerId=void 0;var i=this.adLayer.isAdPlaying(),r=this.adPodQueue.length>0,n=Math.max(250,Math.floor(null!==(e=this.config.adBreakCheckIntervalMs)&&void 0!==e?e:1e3)),a=this.config.maxAdBreakExtensionMs,s="number"==typeof a&&a>0?a:6e4,o=0;null!=this.currentAdBreakStartWallClockMs&&(o=Date.now()-this.currentAdBreakStartWallClockMs);var l=null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:0,u=Math.max(0,o-l);(i||r||this.showAds)&&u<s?this.scheduleAdStopCountdown(n):(i&&this.adLayer.stop().catch(function(){}),this.handleAdPodComplete())}},e.prototype.scheduleAdStartIn=function(e){var t=this;this.clearAdStartTimer();var i=Math.max(0,Math.floor(e));0!==i?this.adStartTimerId=window.setTimeout(function(){t.handleAdStart({type:"start"}).catch(function(){})},i):this.handleAdStart({type:"start"}).catch(function(){})},e.prototype.clearAdStartTimer=function(){null!=this.adStartTimerId&&(clearTimeout(this.adStartTimerId),this.adStartTimerId=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,t,i,r,n,a,s=this;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] 🏁 Ad pod complete - cleaning up"),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.isInAdTransition=!1,this.stopContinuousFetching(),this.stopFillerBreakTimer(),this.hidePlaceholderLayer(),this.clearPendingAdBreak(),this.pendingNextAdBids=null,this.isShowingPlaceholder&&(this.adLayer.hidePlaceholder(),this.isShowingPlaceholder=!1),this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.adPodQueue=[],this.showAds=!1,this.currentAdIndex=0,this.totalAdsInBreak=0,this.totalAdRequestsInBreak=0,this.consecutiveFailures=0;var o=null!==(t=null===(e=this.savedMutedStateBeforeScte)||void 0===e?void 0:e.muted)&&void 0!==t?t:this.adLayer.getOriginalMutedState(),l=null!==(r=null===(i=this.savedMutedStateBeforeScte)||void 0===i?void 0:i.volume)&&void 0!==r?r:this.adLayer.getOriginalVolume();this.adLayer.updateOriginalMutedState(o,l),this.adLayer.stop().catch(function(){}),this.video.muted!==o&&(this.video.muted=o),Math.abs(this.video.volume-l)>.01&&(this.video.volume=l);var u=Mu(),c=void 0!==u.tizenVersion||void 0!==u.webOSVersion;if(c&&this.hls){if(!o){var d=this.hls,h=o,f=l,v=function(){d.off(pu.Events.MANIFEST_PARSED,v),s.inAdBreak||s.adLayer.isAdPlaying()||(s.video.muted!==h&&(s.video.muted=h),Math.abs(s.video.volume-f)>.01&&(s.video.volume=f),s.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Smart TV: audio state restored on MANIFEST_PARSED after re-attach"))};d.on(pu.Events.MANIFEST_PARSED,v)}this.hls.attachMedia(this.video),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Smart TV: re-attached HLS to video element after ad break to restore media pipeline")}this.shouldContinueLiveStreamDuringAds()?(this.config.debugAdTiming&&(this.video.paused?console.log("[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback"):console.log("[StormcloudVideoPlayer] Content video already playing in live mode after ads")),null===(n=this.video.play())||void 0===n||n.catch(function(){})):this.video.paused&&(null===(a=this.video.play())||void 0===a||a.catch(function(){})),this.syncMainContentAudioWhenVisible(),o||(requestAnimationFrame(function(){s.syncMainContentAudioWhenVisible()}),setTimeout(function(){s.syncMainContentAudioWhenVisible()},0),setTimeout(function(){s.syncMainContentAudioWhenVisible()},50),setTimeout(function(){s.syncMainContentAudioWhenVisible()},100),setTimeout(function(){s.syncMainContentAudioWhenVisible()},150)),c&&!o&&[500,1e3,2e3,3e3,5e3].forEach(function(e){setTimeout(function(){s.inAdBreak||s.adLayer.isAdPlaying()||(s.video.muted!==o&&(s.video.muted=o),Math.abs(s.video.volume-l)>.01&&(s.video.volume=l))},e)}),this.savedMutedStateBeforeScte=null},e.prototype.handleAdFailure=function(){this.consecutiveFailures++,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] Ad failure: consecutiveFailures=".concat(this.consecutiveFailures)),this.consecutiveFailures>=this.maxConsecutiveFailures&&(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Max consecutive failures reached (".concat(this.consecutiveFailures,"), ending ad break gracefully")),this.handleAdPodComplete())},e.prototype.startAdRequestWatchdog=function(e){var t,i=this;this.clearAdRequestWatchdog();var r=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adRequestWatchdogToken=e,this.adRequestWatchdogId=window.setTimeout(function(){i.adRequestWatchdogToken===e&&(i.adRequestWatchdogId=void 0,i.adRequestWatchdogToken=null,i.activeAdRequestToken===e&&(i.activeAdRequestToken=null),i.logAdState("ad_request_timeout",{token:e,timeoutMs:r}),i.handleAdFailure())},r),this.logAdState("ad_request_watchdog_started",{token:e,timeoutMs:r})},e.prototype.clearAdRequestWatchdog=function(){null!=this.adRequestWatchdogId&&(clearTimeout(this.adRequestWatchdogId),this.adRequestWatchdogId=void 0),null!=this.adRequestWatchdogToken&&(this.logAdState("ad_request_watchdog_cleared",{token:this.adRequestWatchdogToken}),this.adRequestWatchdogToken=null)},e.prototype.startAdFailsafeTimer=function(e){var t,i=this;this.clearAdFailsafeTimer();var r=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adFailsafeToken=e,this.adFailsafeTimerId=window.setTimeout(function(){i.adFailsafeToken===e&&(i.adFailsafeTimerId=void 0,i.adFailsafeToken=null,i.activeAdRequestToken===e&&(i.activeAdRequestToken=null),i.logAdState("ad_failsafe_triggered",{token:e,failsafeMs:r,videoPaused:i.video.paused,imaAdPlaying:i.adLayer.isAdPlaying()}),i.handleAdFailure())},r),this.logAdState("ad_failsafe_started",{token:e,failsafeMs:r})},e.prototype.clearAdFailsafeTimer=function(){null!=this.adFailsafeTimerId&&(clearTimeout(this.adFailsafeTimerId),this.logAdState("ad_failsafe_cleared",{token:this.adFailsafeToken}),this.adFailsafeTimerId=void 0),this.adFailsafeToken=null},e.prototype.logAdState=function(e,t){void 0===t&&(t={}),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer][AdState]",w({event:e,timestamp:(new Date).toISOString(),showAds:this.showAds,adPlaying:this.adLayer.isAdPlaying(),inAdBreak:this.inAdBreak,activeAdRequestToken:this.activeAdRequestToken},t))},e.prototype.getRemainingAdMs=function(){if(null==this.currentAdBreakStartWallClockMs)return 0;if(null==this.expectedAdBreakDurationMs)return Number.MAX_SAFE_INTEGER;var e=Date.now()-this.currentAdBreakStartWallClockMs;return Math.max(0,this.expectedAdBreakDurationMs-e)},e.prototype.toggleMute=function(){if(this.adLayer.isAdPlaying()){var e=0===this.adLayer.getAdVolume();if(e){var t=this.adLayer.getOriginalVolume()||1;this.adLayer.setAdVolume(t),this.adLayer.updateOriginalMutedState(!1,t)}else{var i=this.adLayer.getAdVolume();this.adLayer.setAdVolume(0),this.adLayer.updateOriginalMutedState(!0,i)}this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Mute toggle during ad:",e?"unmuted":"muted")}else this.video.muted=!this.video.muted,this.adLayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted:",this.video.muted)},e.prototype.toggleFullscreen=function(){var e=this;return new Promise(function(t,i){if(document.fullscreenElement)document.exitFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",t),i(t)});else{var r=e.video.parentElement;if(!r)return void i(new Error("No parent container found for fullscreen"));r.requestFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Fullscreen error:",t),i(t)})}})},e.prototype.isMuted=function(){if(this.adLayer.isAdPlaying()){var e=0===this.adLayer.getAdVolume();return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] isMuted() during ad playback ->",e),e}return this.video.muted},e.prototype.setMuted=function(e){if(this.adLayer.isAdPlaying()){var t=this.adLayer.getOriginalVolume()||1;return this.adLayer.setAdVolume(e?0:t),this.adLayer.updateOriginalMutedState(e,t),void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted applied to ad layer (content stays muted)",{muted:e,savedVolume:t}))}this.video.muted=e,this.inAdBreak||this.adLayer.updateOriginalMutedState(e,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted called:",e)},e.prototype.setVolume=function(e){var t=Math.max(0,Math.min(1,e));if(this.adLayer.isAdPlaying()){this.adLayer.setAdVolume(t);var i=t>0?t:this.adLayer.getOriginalVolume();this.adLayer.updateOriginalMutedState(0===t,i),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:t})}else this.video.volume=t,this.video.muted=0===t,this.inAdBreak||this.adLayer.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume called:",t)},e.prototype.getVolume=function(){return this.adLayer.isAdPlaying()?this.adLayer.getAdVolume():this.video.volume},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.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing player"),this.adLayer&&this.adLayer.isAdPlaying()){var e=this.video.clientWidth||640,t=this.video.clientHeight||480;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing ads manager to ".concat(e,"x").concat(t)),this.adLayer.resize(e,t)}},e.prototype.destroy=function(){var e,t;this.stopContinuousFetching(),this.stopFillerBreakTimer(),this.clearAdStartTimer(),this.clearAdStopTimer(),this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.clearPendingAdBreak(),this.fillerVideo&&(this.fillerVideo.pause(),this.fillerVideo.parentElement&&this.fillerVideo.parentElement.removeChild(this.fillerVideo),this.fillerVideo=void 0),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.adLayer)||void 0===t||t.destroy(),this.consecutiveFailures=0},e}(),Uu={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Gu=z.createContext&&z.createContext(Uu),Vu=["attr","size","title"];function Hu(e,t){if(null==e)return{};var i,r,n=function(e,t){if(null==e)return{};var i={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;i[r]=e[r]}return i}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)i=a[r],t.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}function Ku(){return Ku=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},Ku.apply(this,arguments)}function ju(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function Wu(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ju(Object(i),!0).forEach(function(t){qu(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ju(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function qu(e,t,i){var r;return r=function(e,t){if("object"!=S(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=S(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==S(r)?r:r+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Yu(e){return e&&e.map(function(e,t){return z.createElement(e.tag,Wu({key:t},e.attr),Yu(e.child))})}function zu(e){return function(t){return z.createElement(Xu,Ku({attr:Wu({},e.attr)},t),Yu(e.child))}}function Xu(e){var t=function(t){var i,r=e.attr,n=e.size,a=e.title,s=Hu(e,Vu),o=n||t.size||"1em";return t.className&&(i=t.className),e.className&&(i=(i?i+" ":"")+e.className),z.createElement("svg",Ku({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,r,s,{className:i,style:Wu(Wu({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!==Gu?z.createElement(Gu.Consumer,null,function(e){return t(e)}):t(Uu)}function Qu(e){return zu({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 $u(e){return zu({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 Ju(e){return zu({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 Zu(e){return zu({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 ec(e){return zu({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 tc(e){return zu({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 ic(e){return zu({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 rc(e){return zu({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 nc=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs"],ac=z.memo(function(e){var t=e.src,i=e.autoplay,r=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,m=e.wrapperStyle,p=e.className,y=e.style,E=e.controls,T=e.playsInline,k=e.preload,S=e.poster,A=e.children,b=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=Y.useRef(null),D=Y.useRef(null),C=Y.useRef(null),_=Y.useRef(null),M=Y.useRef(null),O=x(z.useState({showAds:!1,currentIndex:0,totalAds:0}),2),F=O[0],N=O[1],B=x(z.useState(!0),2),U=B[0],G=B[1],V=x(z.useState(!1),2),H=V[0],K=V[1],j=x(z.useState(!1),2),W=j[0],X=j[1],Q=x(z.useState(!1),2),$=Q[0],J=Q[1],Z=x(z.useState(0),2),ee=Z[0],te=Z[1],ie=x(z.useState(0),2),re=ie[0],ne=ie[1],ae=x(z.useState(1),2),se=ae[0],oe=ae[1],le=x(z.useState(1),2),ue=le[0],ce=le[1],de=x(z.useState(!1),2),he=de[0],fe=de[1],ve=x(z.useState(!1),2),ge=ve[0],me=ve[1],pe=x(z.useState(!0),2),ye=pe[0],Ee=pe[1],Te=x(z.useState(!1),2),ke=Te[0],Se=Te[1],Ae=x(z.useState(!1),2),be=Ae[0],Le=Ae[1],Ie=x(z.useState(!1),2),Re=Ie[0],we=Ie[1],Pe=x(z.useState(!0),2),De=Pe[0],Ce=Pe[1],_e=x(z.useState("undefined"!=typeof window?window.innerWidth:1920),2),xe=_e[0],Me=_e[1],Oe=x(z.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),Fe=Oe[0],Ne=Oe[1],Be=xe<480?.7:xe<768?.8:xe<1024?.9:1,Ue=Y.useCallback(function(){_.current&&clearTimeout(_.current),Ce(!0),_.current=window.setTimeout(function(){he||ge||Ce(!1)},3e3)},[he,ge]),Ge=function(e){if(!isFinite(e))return"0:00:00";var t=Math.floor(e/3600),i=Math.floor(e%3600/60),r=Math.floor(e%60);return"".concat(t,":").concat(i.toString().padStart(2,"0"),":").concat(r.toString().padStart(2,"0"))},Ve=function(e){if(D.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));D.current.setVolume(t)}},He=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),Ke=u&&(!He||a),je=Y.useMemo(function(){return nc.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,a,b,n,s]);Y.useEffect(function(){if("undefined"!=typeof window){var e=R.current;if(e&&t){if(!b)return we(!0),void Ee(!1);if(we(!1),D.current){try{D.current.destroy()}catch(e){}D.current=null}var c={src:t,videoElement:e};void 0!==i&&(c.autoplay=i),void 0!==r&&(c.muted=r),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!==b&&(c.licenseKey=b),void 0!==L&&(c.minSegmentsBeforePlay=L);var g=new Bu(c);return D.current=g,g.load().then(function(){var e=g.shouldShowNativeControls();G(e),null==v||v(g)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),Ee(!1),null==v||v(g)}),function(){try{g.destroy()}catch(e){}D.current=null}}}},[je]),Y.useEffect(function(){if(D.current)try{void 0!==i&&D.current.videoElement&&(D.current.videoElement.autoplay=i),void 0===r||D.current.isShowingAds()||D.current.setMuted(r)}catch(e){console.warn("Failed to update player properties:",e)}},[i,r]),Y.useEffect(function(){if(D.current){var e=setInterval(function(){var e,t;if(D.current){var i=D.current.isShowingAds(),r="true"===(null===(t=null===(e=R.current)||void 0===e?void 0:e.dataset)||void 0===t?void 0:t.stormcloudAdPlaying),n=i||r,a=D.current.getCurrentAdIndex(),s=D.current.getTotalAdsInBreak();N(function(e){return e.showAds!==n||e.currentIndex!==a||e.totalAds!==s?(n&&!e.showAds&&Le(!1),{showAds:n,currentIndex:a,totalAds:s}):e})}},50);return function(){return clearInterval(e)}}},[]),Y.useEffect(function(){if("undefined"!=typeof window&&D.current){var e=function(){D.current&&R.current&&"function"==typeof D.current.resize&&D.current.resize(),Me(window.innerWidth),Ne(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),Y.useEffect(function(){if(D.current&&R.current){var e=setInterval(function(){if(D.current&&R.current){K(D.current.isMuted()),J(!R.current.paused);var e=R.current.currentTime;te(isFinite(e)?e:0);var t=R.current.duration;ne(isFinite(t)?t:0);var i=D.current.getVolume();oe(isFinite(i)?Math.max(0,Math.min(1,i)):1);var r=R.current.playbackRate;ce(isFinite(r)&&r>0?r:1)}X(document.fullscreenElement===M.current)},200),t=function(){X(document.fullscreenElement===M.current)};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),Y.useEffect(function(){if(R.current){var e=function(){Ee(!1),C.current&&(clearTimeout(C.current),C.current=null),Se(!1)},t=function(){Ee(!1),C.current&&(clearTimeout(C.current),C.current=null),Se(!1)},i=function(){C.current&&clearTimeout(C.current),C.current=window.setTimeout(function(){Se(!0)},300)},r=function(){Ee(!1),C.current&&(clearTimeout(C.current),C.current=null),Se(!1),Le(!1)},n=function(){var e,t,i,r=(null===(e=D.current)||void 0===e?void 0:e.isShowingAds())||"true"===(null===(i=null===(t=R.current)||void 0===t?void 0:t.dataset)||void 0===i?void 0:i.stormcloudAdPlaying);D.current&&!r?Le(!0):Le(!1)},a=function(){Le(!0)},s=R.current;return s.addEventListener("canplay",e),s.addEventListener("canplaythrough",t),s.addEventListener("waiting",i),s.addEventListener("playing",r),s.addEventListener("pause",n),s.addEventListener("ended",a),s.paused&&Le(!0),function(){C.current&&(clearTimeout(C.current),C.current=null),s.removeEventListener("canplay",e),s.removeEventListener("canplaythrough",t),s.removeEventListener("waiting",i),s.removeEventListener("playing",r),s.removeEventListener("pause",n),s.removeEventListener("ended",a)}}},[l]),Y.useEffect(function(){return function(){_.current&&clearTimeout(_.current)}},[]);var We=Y.useCallback(function(){Ue()},[Ue]),qe=Y.useCallback(function(){he||ge||Ce(!1)},[he,ge]),Ye=re>0?ee/re*100:0,ze=H||0===se?ic:se<.5?tc:rc;return q.jsxs(q.Fragment,{children:[q.jsx("style",{children:"\n @keyframes sc-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes sc-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.6; }\n }\n @keyframes sc-fade-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n .sc-wrapper:fullscreen,\n .sc-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 .sc-ctrl-btn {\n background: none;\n border: none;\n color: #fff;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n padding: 8px;\n transition: background 0.15s ease, opacity 0.15s ease;\n opacity: 0.9;\n }\n .sc-ctrl-btn:hover {\n opacity: 1;\n background: rgba(255, 255, 255, 0.1);\n }\n .sc-ctrl-btn:active {\n opacity: 0.7;\n }\n .sc-controls-bar {\n transition: opacity 0.35s ease, transform 0.35s ease;\n }\n .sc-progress-track:hover .sc-progress-thumb {\n transform: translate(-50%, -50%) scale(1) !important;\n }\n .sc-loading-hidden .sc-loading-indicator {\n display: none !important;\n }\n "}),q.jsxs("div",{ref:M,className:"sc-wrapper ".concat(g||""),onMouseMove:We,onMouseLeave:qe,style:w({display:"flex",alignItems:"center",justifyContent:"center",position:W?"fixed":"relative",top:W?0:void 0,left:W?0:void 0,overflow:"hidden",width:W?"100vw":"100%",height:W?"100vh":"auto",minHeight:W?"100vh":"auto",maxWidth:W?"100vw":"100%",maxHeight:W?"100vh":"none",zIndex:W?999999:void 0,backgroundColor:"#000",borderRadius:W?0:void 0,boxShadow:W?"none":void 0},m),children:[q.jsx("video",w({ref:R,className:p,style:w({display:"block",width:"100%",height:W?"100%":"auto",maxWidth:"100%",maxHeight:W?"100%":"none",objectFit:W?"cover":"contain",backgroundColor:"#000",aspectRatio:W?"unset":void 0},y),controls:U&&E&&!u,playsInline:T,preload:k,poster:S},I,{children:A})),(ye||ke)&&!c&&q.jsx(ec,{className:"sc-loading-indicator",size:40,color:"rgba(255, 255, 255, 0.85)",style:{position:"absolute",top:"calc(50% - 20px)",left:"calc(50% - 20px)",zIndex:20,animation:"sc-spin 0.9s linear infinite",filter:"drop-shadow(0 2px 8px rgba(0, 0, 0, 0.6))"}}),Re&&q.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"rgba(220, 38, 38, 0.92)",backdropFilter:"blur(24px)",color:"white",padding:"28px 36px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",boxShadow:"0 24px 64px rgba(0, 0, 0, 0.5)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[q.jsx("div",{style:{fontSize:"18px",fontWeight:"700",marginBottom:"10px",letterSpacing:"-0.02em"},children:"License Key Required"}),q.jsxs("div",{style:{fontSize:"13px",lineHeight:"1.6",color:"rgba(255, 255, 255, 0.85)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",q.jsx("br",{}),"Contact your administrator for licensing information."]})]}),be&&!ye&&!ke&&!Re&&!F.showAds&&q.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)}),Le(!1)))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"rgba(0, 0, 0, 0.55)",backdropFilter:"blur(20px)",WebkitBackdropFilter:"blur(20px)",borderRadius:"50%",width:"".concat(Math.max(64,80*Be),"px"),height:"".concat(Math.max(64,80*Be),"px"),display:"flex",alignItems:"center",justifyContent:"center",border:"1.5px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.5)",transition:"all 0.25s ease"},onMouseEnter:function(e){var t=e.currentTarget;t.style.background="rgba(255, 255, 255, 0.15)",t.style.borderColor="rgba(255, 255, 255, 0.35)",t.style.transform="translate(-50%, -50%) scale(1.08)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.background="rgba(0, 0, 0, 0.55)",t.style.borderColor="rgba(255, 255, 255, 0.2)",t.style.transform="translate(-50%, -50%) scale(1)"},title:"Play",children:q.jsx(Zu,{size:Math.max(22,28*Be),color:"white",style:{marginLeft:"4px",filter:"drop-shadow(0 1px 3px rgba(0, 0, 0, 0.5))"}})}),F.showAds&&q.jsxs("div",{style:{position:"absolute",top:"".concat(12*Be,"px"),left:"".concat(12*Be,"px"),zIndex:20,display:"flex",alignItems:"center",gap:"8px",animation:"sc-fade-in 0.3s ease"},children:[q.jsx("div",{style:{background:"rgba(234, 179, 8, 0.9)",backdropFilter:"blur(12px)",color:"#000",padding:"".concat(4*Be,"px ").concat(12*Be,"px"),borderRadius:"6px",fontSize:"".concat(11*Be,"px"),fontWeight:"700",letterSpacing:"0.08em",textTransform:"uppercase",boxShadow:"0 2px 12px rgba(234, 179, 8, 0.3)"},children:"Ad"}),F.currentIndex>0&&q.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.5)",backdropFilter:"blur(12px)",color:"rgba(255, 255, 255, 0.8)",padding:"".concat(4*Be,"px ").concat(10*Be,"px"),borderRadius:"6px",fontSize:"".concat(11*Be,"px"),fontWeight:"600",border:"1px solid rgba(255, 255, 255, 0.08)"},children:[F.currentIndex," of ",Math.max(F.totalAds,F.currentIndex)]})]}),Ke&&!Re?q.jsxs("div",{className:"sc-controls-bar",style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(0deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%)",padding:"".concat(20*Be,"px ").concat(12*Be,"px ").concat(8*Be,"px"),zIndex:10,opacity:De||F.showAds?1:0,transform:De||F.showAds?"translateY(0)":"translateY(6px)",pointerEvents:De||F.showAds?"auto":"none"},children:[q.jsxs("div",{className:"sc-progress-track",style:{width:"100%",height:"3px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"1.5px",marginBottom:"".concat(8*Be,"px"),cursor:"pointer",position:"relative",transition:"height 0.1s ease"},onClick:function(e){if(R.current&&re>0&&isFinite(re)){var t=e.currentTarget.getBoundingClientRect(),i=e.clientX-t.left,r=Math.max(0,Math.min(1,i/t.width))*re;isFinite(r)&&r>=0&&r<=re&&(R.current.currentTime=r)}Ue()},onMouseEnter:function(e){e.currentTarget.style.height="5px"},onMouseLeave:function(e){e.currentTarget.style.height="3px"},children:[q.jsx("div",{style:{position:"absolute",top:0,left:0,bottom:0,background:F.showAds?"#f5c518":"#ff0000",borderRadius:"1.5px",width:"".concat(Ye,"%"),transition:"width 0.15s linear"}}),q.jsx("div",{className:"sc-progress-thumb",style:{position:"absolute",top:"50%",left:"".concat(Ye,"%"),transform:"translate(-50%, -50%) scale(0)",width:"13px",height:"13px",background:F.showAds?"#f5c518":"#ff0000",borderRadius:"50%",boxShadow:"0 0 4px rgba(0, 0, 0, 0.3)",transition:"transform 0.1s ease, left 0.15s linear"}})]}),q.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",gap:"".concat(8*Be,"px")},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Be,"px")},children:[q.jsx("button",{className:"sc-ctrl-btn",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)}),Le(!1)):(R.current.pause(),Le(!0)));Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:$?"Pause":"Play",children:$?q.jsx(Ju,{size:Math.max(14,18*Be)}):q.jsx(Zu,{size:Math.max(14,18*Be),style:{marginLeft:"2px"}})}),q.jsxs("div",{style:{display:"flex",alignItems:"center"},onMouseEnter:function(){return fe(!0)},onMouseLeave:function(){return fe(!1)},children:[q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){D.current&&D.current.toggleMute(),null==d||d(),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:H?"Unmute":"Mute",children:q.jsx(ze,{size:Math.max(14,18*Be)})}),q.jsx("div",{style:{width:he?"".concat(62*Be,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:he?"2px":"0",paddingRight:he?"4px":"0"},children:q.jsxs("div",{style:{position:"relative",width:"".concat(56*Be,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,i=function(e){var i=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-i.left)/i.width)))},r=function(){document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",r)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",r);var n=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-t.left)/t.width)))},children:[q.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(255, 255, 255, 0.2)",borderRadius:"1.5px"}}),q.jsx("div",{style:{position:"absolute",top:0,left:0,bottom:0,width:"".concat(100*(H?0:se),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(H?0:se),"%"),transform:"translate(-50%, -50%)",width:"12px",height:"12px",background:"#fff",borderRadius:"50%",boxShadow:"0 0 3px rgba(0, 0, 0, 0.3)",transition:"left 0.1s ease-out"}})]})})]}),q.jsxs("div",{style:{fontSize:"".concat(13*Be,"px"),fontFamily:"Roboto, 'Segoe UI', Arial, sans-serif",color:"rgba(255, 255, 255, 0.9)",display:xe<480?"none":"block",fontVariantNumeric:"tabular-nums",userSelect:"none",marginLeft:"".concat(4*Be,"px")},children:[Ge(ee)," ",q.jsx("span",{style:{color:"rgba(255,255,255,0.5)"},children:"/"})," ",Ge(re)]})]}),q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Be,"px")},children:[q.jsxs("div",{style:{position:"relative",display:xe<600?"none":"block"},children:[q.jsxs("button",{className:"sc-ctrl-btn",onClick:function(){me(!ge),Ue()},style:{padding:"".concat(6*Be,"px ").concat(10*Be,"px"),borderRadius:"".concat(6*Be,"px"),fontSize:"".concat(13*Be,"px"),fontFamily:"'SF Mono', 'Cascadia Code', monospace",fontWeight:"600",minHeight:"".concat(32*Be,"px")},title:"Playback Speed",children:[ue,"x"]}),ge&&q.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"8px",background:"rgba(0, 0, 0, 0.8)",backdropFilter:"blur(24px)",WebkitBackdropFilter:"blur(24px)",borderRadius:"10px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"80px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5)",animation:"sc-fade-in 0.15s ease"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(function(e){return q.jsxs("button",{onClick:function(){return t=e,R.current&&isFinite(t)&&t>0&&(R.current.playbackRate=t),void me(!1);var t},style:{display:"block",width:"100%",padding:"".concat(8*Be,"px ").concat(14*Be,"px"),background:ue===e?"rgba(255, 255, 255, 0.12)":"transparent",border:"none",color:ue===e?"#fff":"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"".concat(12*Be,"px"),fontFamily:"'SF Mono', monospace",fontWeight:ue===e?"700":"500",textAlign:"center",transition:"background 0.15s ease, color 0.15s ease"},onMouseEnter:function(t){ue!==e&&(t.target.style.background="rgba(255, 255, 255, 0.08)",t.target.style.color="#fff")},onMouseLeave:function(t){ue!==e&&(t.target.style.background="transparent",t.target.style.color="rgba(255, 255, 255, 0.7)")},children:[e,"x"]},e)})})]}),q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){h?h():M.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):M.current.requestFullscreen().catch(function(){})),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:W?"Exit Fullscreen":"Enter Fullscreen",children:W?q.jsx(Qu,{size:Math.max(14,18*Be)}):q.jsx($u,{size:Math.max(14,18*Be)})})]})]})]}):u&&!Re&&q.jsxs("div",{className:"sc-controls-bar",style:{position:"absolute",bottom:"".concat(10*Be,"px"),right:"".concat(10*Be,"px"),display:"flex",flexDirection:Fe?"column":"row",gap:"".concat(8*Be,"px"),zIndex:10,opacity:De?1:0,transform:De?"translateY(0)":"translateY(4px)",pointerEvents:De?"auto":"none"},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",background:"rgba(0, 0, 0, 0.6)",borderRadius:"".concat(18*Be,"px"),padding:"2px"},onMouseEnter:function(){return fe(!0)},onMouseLeave:function(){return fe(!1)},children:[q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){D.current&&D.current.toggleMute(),null==d||d(),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:H?"Unmute":"Mute",children:q.jsx(ze,{size:Math.max(14,18*Be)})}),q.jsx("div",{style:{width:he?"".concat(62*Be,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:he?"2px":"0",paddingRight:he?"6px":"0"},children:q.jsxs("div",{style:{position:"relative",width:"".concat(56*Be,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,i=function(e){var i=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-i.left)/i.width)))},r=function(){document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",r)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",r);var n=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-t.left)/t.width)))},children:[q.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(255, 255, 255, 0.2)",borderRadius:"1.5px"}}),q.jsx("div",{style:{position:"absolute",top:0,left:0,bottom:0,width:"".concat(100*(H?0:se),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(H?0:se),"%"),transform:"translate(-50%, -50%)",width:"12px",height:"12px",background:"#fff",borderRadius:"50%",boxShadow:"0 0 3px rgba(0, 0, 0, 0.3)",transition:"left 0.1s ease-out"}})]})})]}),q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){h?h():M.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):M.current.requestFullscreen().catch(function(){})),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px"),background:"rgba(0, 0, 0, 0.6)"},title:W?"Exit Fullscreen":"Enter Fullscreen",children:W?q.jsx(Qu,{size:Math.max(14,18*Be)}):q.jsx($u,{size:Math.max(14,18*Be)})})]}),f&&q.jsx("div",{onClick:f,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var i,r,n,a,s,o;try{for(var l=_(nc),u=l.next();!u.done;u=l.next()){if(e[v=u.value]!==t[v])return!1}}catch(e){i={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(i)throw i.error}}try{for(var 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=_(["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}),sc=function(){},oc={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:sc,onPlay:sc,onPause:sc,onBuffer:sc,onBufferEnd:sc,onEnded:sc,onError:sc,onDuration:sc,onSeek:sc,onProgress:sc,onVolumeToggle:sc,onFullscreenToggle:sc,onControlClick:sc},lc=Y.lazy,uc=function(e,t){var i=w({},e);return t.forEach(function(e){delete i[e]}),i},cc=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},dc=function(e){for(var t,i,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(!r.length)return e;var a=r.shift();if(hc(e)&&hc(a))for(var s in a)hc(a[s])?(e[s]||Object.assign(e,((t={})[s]={},t)),dc(e[s],a[s])):Object.assign(e,((i={})[s]=a[s],i));return dc.apply(void 0,M([e],x(r),!1))},hc=function(e){return e&&"object"===S(e)&&!Array.isArray(e)},fc="undefined"!=typeof window&&window.document,vc="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,gc=fc&&/iPad|iPhone|iPod/.test(navigator.userAgent),mc=fc&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),pc=/\.(m3u8)($|\?)/i,yc=/\/hls\//i,Ec=/\.(mpd)($|\?)/i,Tc=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,kc=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,Sc={hls:function(e){return!(!e||"string"!=typeof e)&&(pc.test(e)||yc.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&Ec.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&Tc.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&kc.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(Tc.test(e)||kc.test(e))}},Ac=function(e){function t(){var t=e.apply(this,M([],x(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return D(t,void 0,void 0,function(){var e,t,i,r,n,a,s,o;return C(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 Bu(e),null===(r=(i=this.props).onMount)||void 0===r||r.call(i,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,i,r;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 i,r;console.error("[HlsPlayer] Failed to play:",e),null===(r=(i=t.props).onError)||void 0===r||r.call(i,e)}),null===(r=(i=t.props).onPlay)||void 0===r||r.call(i)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},t.pause=function(){var e,i;t.props.videoElement&&(t.props.videoElement.pause(),null===(i=(e=t.props).onPause)||void 0===i||i.call(e))},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,i){t.props.videoElement&&(t.props.videoElement.currentTime=e,i||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=Sc.hls,t}(Y.Component),bc=function(e){function t(){var t=e.apply(this,M([],x(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,i;if(t.props.videoElement&&t.props.src){var r=t.props.videoElement,n=function(){var e,i;t.mounted&&!t.ready&&(t.ready=!0,null===(i=(e=t.props).onReady)||void 0===i||i.call(e))},a=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onPlay)||void 0===i||i.call(e))},s=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onPause)||void 0===i||i.call(e))},o=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onEnded)||void 0===i||i.call(e))},l=function(e){var i,r;t.mounted&&(null===(r=(i=t.props).onError)||void 0===r||r.call(i,e))},u=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onLoaded)||void 0===i||i.call(e))};return r.addEventListener("loadedmetadata",n),r.addEventListener("play",a),r.addEventListener("pause",s),r.addEventListener("ended",o),r.addEventListener("error",l),r.addEventListener("loadeddata",u),r.src=t.props.src,void 0!==t.props.autoplay&&(r.autoplay=t.props.autoplay),void 0!==t.props.muted&&(r.muted=t.props.muted),void 0!==t.props.loop&&(r.loop=t.props.loop),void 0!==t.props.controls&&(r.controls=t.props.controls),void 0!==t.props.playsInline&&(r.playsInline=t.props.playsInline),void 0!==t.props.preload&&(r.preload=t.props.preload),void 0!==t.props.poster&&(r.poster=t.props.poster),null===(i=(e=t.props).onMount)||void 0===i||i.call(e,t),function(){r.removeEventListener("loadedmetadata",n),r.removeEventListener("play",a),r.removeEventListener("pause",s),r.removeEventListener("ended",o),r.removeEventListener("error",l),r.removeEventListener("loadeddata",u)}}},t.play=function(){var e;if(t.props.videoElement){var i=t.props.videoElement;i.src||i.currentSrc&&""!==i.currentSrc||i.readyState>=1?null===(e=i.play())||void 0===e||e.catch(function(e){var i,r;console.error("[FilePlayer] Failed to play:",e),null===(r=(i=t.props).onError)||void 0===r||r.call(i,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,i){t.props.videoElement&&(t.props.videoElement.currentTime=e,i||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 D(t,void 0,void 0,function(){var e;return C(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 D(t,void 0,void 0,function(){var e;return C(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=Sc.file,t}(Y.Component),Lc=[{key:"hls",name:"HLS Player",canPlay:Sc.hls,lazyPlayer:lc(function(){return Promise.resolve({default:Ac})})},{key:"file",name:"File Player",canPlay:Sc.file,canEnablePIP:function(e){return Sc.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:lc(function(){return Promise.resolve({default:bc})})}],Ic=function(e){function t(){var t=e.apply(this,M([],x(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,i;if(t.props.src&&t.player&&t.isReady){var r=t.getCurrentTime()||0,n=t.getSecondsLoaded(),a=t.getDuration();if(a){var s={playedSeconds:r,played:r/a,loaded:0,loadedSeconds:0};null!==n&&(s.loadedSeconds=n,s.loaded=n/a),s.playedSeconds===t.prevPlayed&&s.loadedSeconds===t.prevLoaded||null===(i=(e=t.props).onProgress)||void 0===i||i.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,i=e.onReady,r=e.playing,n=e.volume,a=e.muted;i(),a||null===n||t.player.setVolume(n),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):r&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,i=e.onStart,r=e.onPlay,n=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==n&&t.player.setPlaybackRate(n),null==i||i(),t.startOnPlay=!1),null==r||r(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var i,r;t.isPlaying=!1,t.isLoading||null===(r=(i=t.props).onPause)||void 0===r||r.call(i,e)},t.handleEnded=function(){var e=t.props,i=e.activePlayer,r=e.loop,n=e.onEnded;i.loopOnEnded&&r&&t.seekTo(0),r||(t.isPlaying=!1,null==n||n())},t.handleError=function(){for(var e,i,r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];t.isLoading=!1,null===(i=(e=t.props).onError)||void 0===i||i.call(e,r[0],r[1],r[2],r[3])},t.handleDurationCheck=function(){var e,i;clearTimeout(t.durationCheckTimeout);var r=t.getDuration();r?t.onDurationCalled||(null===(i=(e=t.props).onDuration)||void 0===i||i.call(e,r),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 i=this.props,r=i.src,n=i.playing,a=i.volume,s=i.muted,o=i.playbackRate,l=i.loop,u=i.activePlayer;if(e.src!==r){if(this.isLoading&&!u.forceLoad&&!cc(r))return console.warn("StormcloudPlayer: the attempt to load ".concat(r," is being deferred until the player has loaded")),void(this.loadOnReady=r||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(r,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,i){var r=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,i):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,i)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){r.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=oc,t}(Y.Component),Rc="undefined"!=typeof window&&window.document,wc="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,Pc=Rc||wc?Y.Suspense:function(){return null},Dc=["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"],Cc=[],_c=function(e,t){var i;return i=function(i){function r(){var r=i.apply(this,M([],x(arguments),!1))||this;return r.state={showPreview:!1},r.references={wrapper:function(e){r.wrapper=e},player:function(e){r.player=e}},r.getActivePlayer=function(i){var r,n;if(!i)return null;try{for(var a=_(M(M([],x(Cc),!1),x(e),!1)),s=a.next();!s.done;s=a.next()){var o=s.value;if(o.canPlay(i))return o}}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return t||null},r.getAttributes=function(e){return uc(r.props,Dc)},r.handleReady=function(){var e,t;null===(t=(e=r.props).onReady)||void 0===t||t.call(e,r)},r.seekTo=function(e,t,i){if(!r.player)return null;r.player.seekTo(e,t,i)},r.getCurrentTime=function(){return r.player?r.player.getCurrentTime():null},r.getSecondsLoaded=function(){return r.player?r.player.getSecondsLoaded():null},r.getDuration=function(){return r.player?r.player.getDuration():null},r.getInternalPlayer=function(e){return void 0===e&&(e="player"),r.player?r.player.getInternalPlayer(e):null},r.renderActivePlayer=function(e){if(!e)return null;var t=r.getActivePlayer(e);return t?z.createElement(Ic,w(w({},r.props),{key:t.key,ref:r.references.player,activePlayer:t.lazyPlayer||t,onReady:r.handleReady})):null},r}return R(r,i),r.prototype.render=function(){var e=this.props,t=e.src,i=e.style,r=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({},i),{width:r,height:n})},o),z.createElement(Pc,{fallback:a},this.renderActivePlayer(t)))},r}(Y.Component),i.displayName="StormcloudPlayer",i.defaultProps=w(w({},oc),{fallback:null,wrapper:"div"}),i.addCustomPlayer=function(e){Cc.push(e)},i.removeCustomPlayers=function(){Cc.length=0},i.canPlay=function(t){var i,r;try{for(var n=_(M(M([],x(Cc),!1),x(e),!1)),a=n.next();!a.done;a=n.next()){if(a.value.canPlay(t))return!0}}catch(e){i={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return!1},i.canEnablePIP=function(t){var i,r;try{for(var n=_(M(M([],x(Cc),!1),x(e),!1)),a=n.next();!a.done;a=n.next()){var s=a.value;if(s.canEnablePIP&&s.canEnablePIP(t))return!0}}catch(e){i={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return!1},i},xc=_c(Lc,Lc[Lc.length-1]);e.IS_BROWSER=fc,e.IS_GLOBAL=vc,e.IS_IOS=gc,e.IS_SAFARI=mc,e.SUPPORTS_DASH=function(){if(!fc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!fc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=xc,e.StormcloudVideoPlayer=Bu,e.StormcloudVideoPlayerComponent=ac,e.canPlay=Sc,e.createPrebidAdLayer=bu,e.createPrebidManager=Eu,e.createStormcloudPlayer=_c,e.default=ac,e.detectBrowser=Mu,e.getBrowserConfigOverrides=Nu,e.getBrowserID=Ru,e.getClientInfo=Iu,e.initializePolyfills=xu,e.isMediaStream=cc,e.lazy=lc,e.logBrowserInfo=Fu,e.merge=dc,e.omit=uc,e.parseQuery=function(e){var t={},i=e.split("?")[1]||"";if(!i)return t;var r=function(e){e.split("&").forEach(function(e){var i=x(e.split("="),2),r=i[0],n=i[1];if(r)try{t[decodeURIComponent(r)]=n?decodeURIComponent(n.replace(/\+/g," ")):""}catch(e){t[r]=n||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(i).forEach(function(e,i){t[i]=e}),t}catch(e){r(i)}else r(i);return t},e.players=Lc,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.sendHeartbeat=_u,e.sendInitialTracking=Du,e.supportsFeature=function(e){switch(e){case"ima":return Ou();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 i(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function r(e){if(Array.isArray(e))return e}function n(e,t,i){return t=c(t),g(e,h()?Reflect.construct(t,i||[],c(e).constructor):t.apply(e,i))}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,k(r.key),r)}}function o(e,t,i){return t&&s(e.prototype,t),i&&s(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(e,t,i){return(t=k(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function u(){return u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,i){var r=y(e,t);if(r){var n=Object.getOwnPropertyDescriptor(r,t);return n.get?n.get.call(arguments.length<3?e:i):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&&m(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 m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}function p(e,t){return r(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,n,a,s,o=[],l=!0,u=!1;try{if(a=(i=i.call(e)).next,0===t){if(Object(i)!==i)return;l=!1}else for(;!(l=(r=a.call(i)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=i.return&&(s=i.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}(e,t)||A(e,t)||v()}function y(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=c(e)););return e}function E(e,t,i,r){var n=u(c(1&r?e.prototype:e),t,i);return 2&r&&"function"==typeof n?function(e){return n.apply(i,e)}:n}function T(e){return function(e){if(Array.isArray(e))return i(e)}(e)||f(e)||A(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 k(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=typeof r)return r;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 A(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}function b(e){var i,r;function n(i,r){try{var s=e[i](r),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var r="return"===i?"return":"next";if(!o.k||t.done)return n(r,t);t=e[r](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":i.resolve({value:t,done:!0});break;case"throw":i.reject(t);break;default:i.resolve({value:t,done:!1})}(i=i.next)?n(i.key,i.arg):r=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};r?r=r.next=o:(i=r=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,i)}function i(){return function(e,t,i){if(h())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var n=new(e.bind.apply(e,r));return i&&m(n,i.prototype),n}(e,arguments,c(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),m(i,e)},L(e)}b.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},b.prototype.next=function(e){return this._invoke("next",e)},b.prototype.throw=function(e){return this._invoke("throw",e)},b.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 i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},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 i(){this.constructor=e}I(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var w=function(){return w=Object.assign||function(e){for(var t,i=1,r=arguments.length;i<r;i++)for(var n in t=arguments[i])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},w.apply(this,arguments)};function P(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]])}return i}function D(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})}function C(e,t){var i,r,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(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,r&&(n=2&o[0]?r.return:o[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,o[1])).done)return n;switch(r=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++,r=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],r=0}finally{i=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function _(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],r=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function x(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var r,n,a=i.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)s.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return s}function M(e,t,i){if(i||2===arguments.length)for(var r,n=0,a=t.length;n<a;n++)!r&&n in t||(r||(r=Array.prototype.slice.call(t,0,n)),r[n]=t[n]);return e.concat(r||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:{}},B={};var U,G={exports:{}},V={};function H(){if(U)return V;U=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),r=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 m(e,t,i){this.props=e,this.context=t,this.refs=g,this.updater=i||f}function p(){}function y(e,t,i){this.props=e,this.context=t,this.refs=g,this.updater=i||f}m.prototype.isReactComponent={},m.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")},m.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},p.prototype=m.prototype;var E=y.prototype=new p;E.constructor=y,v(E,m.prototype),E.isPureReactComponent=!0;var T=Array.isArray;function k(){}var A={H:null,A:null,T:null,S:null},b=Object.prototype.hasOwnProperty;function L(t,i,r){var n=r.ref;return{$$typeof:e,type:t,key:i,ref:void 0!==n?n:null,props:r}}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?(i=""+e.key,r={"=":"=0",":":"=2"},"$"+i.replace(/[=:]/g,function(e){return r[e]})):t.toString(36);var i,r}function P(i,r,n,a,s){var o=S(i);"undefined"!==o&&"boolean"!==o||(i=null);var l,u,d=!1;if(null===i)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(i.$$typeof){case e:case t:d=!0;break;case c:return P((d=i._init)(i._payload),r,n,a,s)}}if(d)return s=s(i),d=""===a?"."+w(i,0):a,T(s)?(n="",null!=d&&(n=d.replace(R,"$&/")+"/"),P(s,r,n,"",function(e){return e})):null!=s&&(I(s)&&(l=s,u=n+(null==s.key||i&&i.key===s.key?"":(""+s.key).replace(R,"$&/")+"/")+d,s=L(l.type,u,l.props)),r.push(s)),1;d=0;var f,v=""===a?".":a+":";if(T(i))for(var g=0;g<i.length;g++)d+=P(a=i[g],r,n,o=v+w(a,g),s);else if("function"==typeof(g=null===(f=i)||"object"!==S(f)?null:"function"==typeof(f=h&&f[h]||f["@@iterator"])?f:null))for(i=g.call(i),g=0;!(a=i.next()).done;)d+=P(a=a.value,r,n,o=v+w(a,g++),s);else if("object"===o){if("function"==typeof i.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(k,k):(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}(i),r,n,a,s);throw r=String(i),Error("Objects are not valid as a React child (found: "+("[object Object]"===r?"object with keys {"+Object.keys(i).join(", ")+"}":r)+"). If you meant to render a collection of children, use an array instead.")}return d}function D(e,t,i){if(null==e)return e;var r=[],n=0;return P(e,r,"","",function(e){return t.call(i,e,n++)}),r}function C(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 _="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)},x={map:D,forEach:function(e,t,i){D(e,function(){t.apply(this,arguments)},i)},count:function(e){var t=0;return D(e,function(){t++}),t},toArray:function(e){return D(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 V.Activity=d,V.Children=x,V.Component=m,V.Fragment=i,V.Profiler=n,V.PureComponent=y,V.StrictMode=r,V.Suspense=l,V.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,V.__COMPILER_RUNTIME={__proto__:null,c:function(e){return A.H.useMemoCache(e)}},V.cache=function(e){return function(){return e.apply(null,arguments)}},V.cacheSignal=function(){return null},V.cloneElement=function(e,t,i){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var r=v({},e.props),n=e.key;if(null!=t)for(a in void 0!==t.key&&(n=""+t.key),t)!b.call(t,a)||"key"===a||"__self"===a||"__source"===a||"ref"===a&&void 0===t.ref||(r[a]=t[a]);var a=arguments.length-2;if(1===a)r.children=i;else if(1<a){for(var s=Array(a),o=0;o<a;o++)s[o]=arguments[o+2];r.children=s}return L(e.type,n,r)},V.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},V.createElement=function(e,t,i){var r,n={},a=null;if(null!=t)for(r in void 0!==t.key&&(a=""+t.key),t)b.call(t,r)&&"key"!==r&&"__self"!==r&&"__source"!==r&&(n[r]=t[r]);var s=arguments.length-2;if(1===s)n.children=i;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(r in s=e.defaultProps)void 0===n[r]&&(n[r]=s[r]);return L(e,a,n)},V.createRef=function(){return{current:null}},V.forwardRef=function(e){return{$$typeof:o,render:e}},V.isValidElement=I,V.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:C}},V.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},V.startTransition=function(e){var t=A.T,i={};A.T=i;try{var r=e(),n=A.S;null!==n&&n(i,r),"object"===S(r)&&null!==r&&"function"==typeof r.then&&r.then(k,_)}catch(e){_(e)}finally{null!==t&&null!==i.types&&(t.types=i.types),A.T=t}},V.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},V.use=function(e){return A.H.use(e)},V.useActionState=function(e,t,i){return A.H.useActionState(e,t,i)},V.useCallback=function(e,t){return A.H.useCallback(e,t)},V.useContext=function(e){return A.H.useContext(e)},V.useDebugValue=function(){},V.useDeferredValue=function(e,t){return A.H.useDeferredValue(e,t)},V.useEffect=function(e,t){return A.H.useEffect(e,t)},V.useEffectEvent=function(e){return A.H.useEffectEvent(e)},V.useId=function(){return A.H.useId()},V.useImperativeHandle=function(e,t,i){return A.H.useImperativeHandle(e,t,i)},V.useInsertionEffect=function(e,t){return A.H.useInsertionEffect(e,t)},V.useLayoutEffect=function(e,t){return A.H.useLayoutEffect(e,t)},V.useMemo=function(e,t){return A.H.useMemo(e,t)},V.useOptimistic=function(e,t){return A.H.useOptimistic(e,t)},V.useReducer=function(e,t,i){return A.H.useReducer(e,t,i)},V.useRef=function(e){return A.H.useRef(e)},V.useState=function(e){return A.H.useState(e)},V.useSyncExternalStore=function(e,t,i){return A.H.useSyncExternalStore(e,t,i)},V.useTransition=function(){return A.H.useTransition()},V.version="19.2.4",V}var K;G.exports;function j(){return K||(K=1,G.exports=H()),G.exports}var W;N.exports;var q=(W||(W=1,N.exports=function(){if(F)return B;F=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(t,i,r){var n=null;if(void 0!==r&&(n=""+r),void 0!==i.key&&(n=""+i.key),"key"in i)for(var a in r={},i)"key"!==a&&(r[a]=i[a]);else r=i;return i=r.ref,{$$typeof:e,type:t,key:n,ref:void 0!==i?i:null,props:r}}return B.Fragment=t,B.jsx=i,B.jsxs=i,B}()),N.exports),Y=j(),z=O(Y),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",ie="level",re="audioTrack",ne="subtitleTrack",ae="main",se="audio",oe="subtitle",le=function(){return o(function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=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_=i,this.totalWeight_=r},[{key:"sample",value:function(e,t){var i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*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,i,r){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_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new le(t),this.fast_=new le(i),this.defaultTTFB_=n,this.ttfb_=new le(t)},[{key:"update",value:function(e,t){var i=this.slow_,r=this.fast_,n=this.ttfb_;i.halfLife!==e&&(this.slow_=new le(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new le(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new le(e,n.getEstimate(),n.getTotalWeight()))}},{key:"sample",value:function(e,t){var i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}},{key:"sampleTTFB",value:function(e){var t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,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,i){return(t=function(e){var t=function(e,t){if("object"!=S(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=S(r))return r;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:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function de(){return de=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},de.apply(null,arguments)}function he(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function fe(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?he(Object(i),!0).forEach(function(t){ce(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):he(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}var ve=o(function e(t,i){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 r="[".concat(t,"]:");this.trace=ge,this.debug=i.debug.bind(null,r),this.log=i.log.bind(null,r),this.warn=i.warn.bind(null,r),this.info=i.info.bind(null,r),this.error=i.error.bind(null,r)}),ge=function(){},me={trace:ge,debug:ge,log:ge,warn:ge,info:ge,error:ge};function pe(){return de({},me)}function ye(e,t,i){return t[e]?t[e].bind(t):function(e,t){var i=self.console[e];return i?i.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):ge}(e,i)}var Ee=pe();var Te=Ee;function ke(){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 i=Object.keys(e),r=Object.keys(t),n=i.length,a=r.length;return!n||!a||n===a&&!i.some(function(e){return-1===r.indexOf(e)})}function Ae(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if("undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(e);if(t){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.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 be(e){for(var t="",i=0;i<e.length;i++){var r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}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,i,r,n,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.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 r.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=i.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=r.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(we)),we.exports),De=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}}),Ce="audio",_e="video",xe="audiovideo",Me=function(){return o(function e(t){var i,r,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=Be(i=this,r="stats"))&&(n.enumerable=!0,Object.defineProperty(i,r,n))},[{key:"setByteRange",value:function(e,t){var i,r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}},{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({},Ce,null),_e,null),xe,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 De),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[Ce]=null,e[_e]=null,e[xe]=null}}])}();function Oe(e){return"initSegment"!==e.sn}var Fe=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[i]))._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=e,r}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],i=this.byteRange[1];if(X(t)&&X(i))return i-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 i=Object.keys(t);if(1===i.length){var r=this._decryptdata=t[i[0]]||null;r&&(this._decryptdata=r.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,i=Object.keys(this.levelkeys),r=i.length;if(r>1||1===r&&null!=(t=this.levelkeys[i[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 i,r=t[e];!r||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=r.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,i,r,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,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a}}}])}(Me),Ne=function(e){function t(e,i,r,s,o){var l;a(this,t),(l=n(this,t,[r])).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=i,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 Be(e,t){var i=Object.getPrototypeOf(e);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r||Be(i,t)}}var Ue=Math.pow(2,32)-1,Ge=[].push,Ve={video:1,audio:2,id3:3,text:4};function He(e){return String.fromCharCode.apply(null,e)}function Ke(e,t){var i=e[t]<<8|e[t+1];return i<0?65536+i:i}function je(e,t){var i=qe(e,t);return i<0?4294967296+i:i}function We(e,t){var i=je(e,t);return i*=Math.pow(2,32),i+=je(e,t+4)}function qe(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Ye(e,t){var i=[];if(!t.length)return i;for(var r=e.byteLength,n=0;n<r;){var a=je(e,n),s=a>1?n+a:r;if(He(e.subarray(n+4,n+8))===t[0])if(1===t.length)i.push(e.subarray(n+8,s));else{var o=Ye(e.subarray(n+8,s),t.slice(1));o.length&&Ge.apply(i,o)}n=s}return i}function ze(e){var t=[],i=e[0],r=8,n=je(e,r);r+=4;var a=0,s=0;0===i?(a=je(e,r),s=je(e,r+4),r+=8):(a=We(e,r),s=We(e,r+8),r+=16),r+=2;var o=e.length+s,l=Ke(e,r);r+=2;for(var u=0;u<l;u++){var c=r,d=je(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return Te.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,r=c+=4}return{earliestPresentationTime:a,timescale:n,version:i,referencesCount:l,references:t}}function Xe(e){for(var t=[],i=Ye(e,["moov","trak"]),r=0;r<i.length;r++){var n=i[r],a=Ye(n,["tkhd"])[0];if(a){var s=a[0],o=je(a,0===s?12:20),l=Ye(n,["mdia","mdhd"])[0];if(l){var u=je(l,0===(s=l[0])?12:20),c=Ye(n,["mdia","hdlr"])[0];if(c){var d=He(c.subarray(8,12)),h={soun:Ce,vide:_e}[d],f=Qe(Ye(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 Ye(e,["moov","mvex","trex"]).forEach(function(e){var i=je(e,4),r=t[i];r&&(r.default={duration:je(e,12),flags:je(e,20)})}),t}function Qe(e){var t,i=e.subarray(8),r=i.subarray(86),n=He(i.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=Ye(i,[n])[0];Ye(o.subarray("enca"===n?28:78),["sinf"]).forEach(function(e){var t=Ye(e,["schm"])[0];if(t){var i=He(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=Ye(e,["frma"])[0];r&&(a=He(r))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=Ye(r,["avcC"])[0];u&&u.length>3&&(a+="."+Ze(u[1])+Ze(u[2])+Ze(u[3]),t=$e("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var c=Ye(i,[n])[0],d=Ye(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++],m=(248&g)>>3;31===m&&(m+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+m}break;case"hvc1":case"hev1":var p=Ye(r,["hvcC"])[0];if(p&&p.length>12){var y=p[1],E=["","A","B","C"][y>>6],T=31&y,k=je(p,2),S=(32&y)>>5?"H":"L",A=p[12],b=p.subarray(6,12);a+="."+E+T,a+="."+function(e){for(var t=0,i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}(k).toString(16).toUpperCase(),a+="."+S+A;for(var L="",I=b.length;I--;){var R=b[I];if(R||L)L="."+R.toString(16).toUpperCase()+L}a+=L}t=$e("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=$e(a,r)||a;break;case"vp09":var w=Ye(r,["vpcC"])[0];if(w&&w.length>6){var P=w[4],D=w[5],C=w[6]>>4&15;a+="."+et(P)+"."+et(D)+"."+et(C)}break;case"av01":var _=Ye(r,["av1C"])[0];if(_&&_.length>2){var x=_[1]>>>5,M=31&_[1],O=_[2]>>>7?"H":"M",F=(64&_[2])>>6,N=(32&_[2])>>5,B=2===x&&F?N?12:10:F?10:8,U=(16&_[2])>>4,G=(8&_[2])>>3,V=(4&_[2])>>2,H=3&_[2];a+="."+x+"."+et(M)+O+"."+et(B)+"."+U+"."+G+V+H+"."+et(1)+"."+et(1)+"."+et(1)+".0",t=$e("dav1",r)}}return{codec:a,encrypted:s,supplemental:t}}function $e(e,t){var i=Ye(t,["dvvC"]),r=i.length?i[0]:Ye(t,["dvcC"])[0];if(r){var n=r[2]>>1&127,a=r[2]<<5&32|r[3]>>3&31;return e+"."+et(n)+"."+et(a)}}function Je(e,t){for(var i=t+5;128&e[t++]&&t<i;);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){Ye(e,["moov","trak"]).forEach(function(e){var i=Ye(e,["mdia","minf","stbl","stsd"])[0];if(i){var r=i.subarray(8),n=Ye(r,["enca"]),a=n.length>0;a||(n=Ye(r,["encv"])),n.forEach(function(e){Ye(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var i=it(e);i&&t(i,a)})})}})}function it(e){var t=Ye(e,["schm"])[0];if(t){var i=He(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=Ye(e,["schi","tenc"])[0];if(r)return r}}}function rt(e,t){var i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function nt(e,t){var i=[],r=t.samples,n=t.timescale,a=t.id,s=!1;return Ye(r,["moof"]).map(function(o){var l=o.byteOffset-8;Ye(o,["traf"]).map(function(o){var u=Ye(o,["tfdt"]).map(function(e){var t=e[0],i=je(e,4);return 1===t&&(i*=Math.pow(2,32),i+=je(e,8)),i/n})[0];return void 0!==u&&(e=u),Ye(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),m=8;c===a&&(!!(1&d)&&(m+=8),!!(2&d)&&(m+=4),!!(8&d)&&(h=je(u,m),m+=4),f&&(v=je(u,m),m+=4),g&&(m+=4),"video"===t.type&&(s=at(t.codec)),Ye(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),m=0,p=!!(512&u),y=0,E=!!(1024&u),T=!!(2048&u),k=0,S=je(a,4),A=8;c&&(d=je(a,A),A+=4),f&&(A+=4);for(var b=d+l,L=0;L<S;L++){if(g?(m=je(a,A),A+=4):m=h,p?(y=je(a,A),A+=4):y=v,E&&(A+=4),T&&(k=0===o?je(a,A):qe(a,A),A+=4),t.type===_e)for(var I=0;I<y;){var R=je(r,b);if(st(s,r[b+=4]))ot(r.subarray(b,b+R),s?2:1,e+k/n,i);b+=R,I+=R+4}e+=m/n}}))})})}),i}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 i=t>>1&63;return 39===i||40===i}return 6===(31&t)}function ot(e,t,i,r){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){Te.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,m=g?2+3*(31&v):0,p=new Uint8Array(m);if(g){p[0]=v;for(var y=1;y<m;y++)p[y]=n[c++]}r.push({type:f,payloadType:s,pts:i,bytes:p})}}}}}else if(5===s&&o>16){for(var E=[],T=0;T<16;T++){var k=n[c++].toString(16);E.push(1==k.length?"0"+k:k),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var S=o-16,A=new Uint8Array(S),b=0;b<S;b++)A[b]=n[c++];r.push({payloadType:s,pts:i,uuid:E.join(""),userData:Ae(A),userDataBytes:A})}}}function lt(e){for(var t=e.byteLength,i=[],r=1;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;var n=t-i.length,a=new Uint8Array(n),s=0;for(r=0;r<n;s++,r++)s===i[0]&&(s++,i.shift()),a[r]=e[s];return a}function ut(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");var r,n;r=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var n=i.length,a=8,s=n;s--;)a+=i[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(i[s],a),a+=i[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,i)}function ct(e){var t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:i,size:t};var a=e.buffer,s=be(new Uint8Array(a,i+12,16)),o=null,l=0;if(0===n)l=28;else{var u=e.getUint32(28);if(!u||r<32+16*u)return{offset:i,size:t};o=[];for(var c=0;c<u;c++)o.push(new Uint8Array(a,i+32+16*c,16));l=32+16*u}if(!l)return{offset:i,size:t};var d=e.getUint32(l);return t-32<d?{offset:i,size:t}:{version:n,systemId:s,kids:o,data:new Uint8Array(a,i+l+4,d),offset:i,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 i=ht[t];return!!i&&!!i[e.slice(0,4)]}function vt(e,t){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!gt(e,t,i)})}function gt(e,t){var i,r=ke(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(i=null==r?void 0:r.isTypeSupported(mt(e,t)))&&i}function mt(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function pt(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,i){var r=t&&at(i)?9:ht.video[i];return r?(2*r+e)/(e?3:2):(ht.audio[i]+e)/(e?2:1)},0)}var Et={};var Tt=/flac|opus|mp4a\.40\.34/i;function kt(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(Tt,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(Et[e])return Et[e];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],r=0;r<i.length;r++){var n;if(gt(i[r],"audio",t))return Et[e]=i[r],i[r];if("mp3"===i[r]&&null!=(n=ke(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))&&(At(e,"audio")||At(e,"video")))return e;if(t){var i=t.split(",");if(i.length>1){if(e)for(var r=i.length;r--;)if(i[r].substring(0,4)===e.substring(0,4))return i[r];return i[0]}}return t||e}function At(e,t){return ft(e,t)&>(e,t)}function bt(e){if(e.startsWith("av01.")){for(var t=e.split("."),i=["0","111","01","01","01","0"],r=t.length;r>4&&r<10;r++)t[r]=i[r-4];return t.join(".")}return e}function Lt(e){var t=ke(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 Dt(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.videoCodec;if(!n&&!e.audioCodec||!i)return Promise.resolve(wt);for(var a=[],s=function(e){var t,i=null==(t=e.videoCodec)?void 0:t.split(","),r=_t(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map(function(e){var t={contentType:mt(bt(e),"video"),width:n,height:a,bitrate:r,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,i){var r,n=null==(r=e.audioCodec)?void 0:r.split(","),a=_t(e);if(n&&e.audioGroups)return e.audioGroups.reduce(function(e,r){var s,o=r?null==(s=t.groups[r])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===r){var s=parseFloat(t.channels||"");n.forEach(function(t){var r={contentType:mt(t,"audio"),bitrate:i?Ct(t,a):a};s&&(r.channels=""+s),e.push(r)})}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="",i=e.audio,r=e.video;if(r){var n=It(r.contentType);t+="".concat(n,"_r").concat(r.height,"x").concat(r.width,"f").concat(Math.ceil(r.framerate)).concat(r.transferFunction||"sd","_").concat(Math.ceil(r.bitrate/1e5))}if(i){var a=It(i.contentType);t+="".concat(r?"_":"").concat(a,"_c").concat(i.channels)}return t}(e);return r[t]||(r[t]=i.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 Ct(e,t){if(t<=1)return 1;var i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function _t(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var xt=["NONE","TYPE-0","TYPE-1",null];var Mt=["SDR","PQ","HLG"];var Ot="",Ft="YES",Nt="v2";function Bt(e){var t=e.canSkipUntil,i=e.canSkipDateRanges,r=e.age;return t&&r<t/2?i?Nt:Ft:Ot}var Ut=function(){return o(function e(t,i,r){a(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=i,this.skip=r},[{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 i;this.supplemental=t.supplemental;var r=null==(i=t.supplemental)?void 0:i.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=",".concat(r.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 Vt(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return Vt(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 i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(t)&&i.push(t)}else if("text"===e){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(t)&&r.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 Vt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Ht(e,t){var i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){var n="SDR"!==(r=t.allowedVideoRanges||Mt.slice(0)).join("")&&!t.videoCodec;(i=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}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}var Kt=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(i,r){if(e&&(r=e(i,r)),"object"===S(r)&&null!==r){if(t.has(r))return;t.add(r)}return r}}(t))};function jt(e,t){Te.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function Wt(e){return e.reduce(function(e,t){var i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);var r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function qt(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function Yt(e,t,i){if("attrs"in e){var r=t.indexOf(e);if(-1!==r)return r}for(var n=0;n<t.length;n++){if(zt(e,t[n],i))return n}return-1}function zt(e,t,i){var r=e.groupId,n=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===r||t.groupId===r)&&(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]:"",i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some(function(e){return-1===r.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function Xt(e,t){var i=e.audioCodec,r=e.channels;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function Qt(e,t,i){for(var r=t;r>-1;r--)if(i(e[r]))return r;for(var n=t+1;n<e.length;n++)if(i(e[n]))return n;return-1}function $t(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}var Jt=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["abr",e.logger])).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.supportedCache={},i.bwEstimator=void 0,i._abandonRulesCheck=function(e){var t,r=i,n=r.fragCurrent,a=r.partCurrent,s=r.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=i._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var m=g>-1&&g!==v,p=!!e||m;if(p||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(p||null!==y){var E=i.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(!(h<=Math.max(E,d/(2*T)*1e3))){var k=y?y.len/T:0,S=c.loading.first?c.loading.first-c.loading.start:-1,A=c.loaded&&S>-1,b=i.getBwEstimate(),L=s.levels,I=L[v],R=Math.max(c.loaded,Math.round(d*(n.bitrate||I.averageBitrate)/8)),w=A?h-S:h;w<1&&A&&(w=Math.min(h,8*c.loaded/b));var P=A?1e3*c.loaded/w:0,D=E/1e3,C=P?(R-c.loaded)/P:8*R/b+D;if(!(C<=k)){var _,x=P?8*P:b,M=!0===(null==(t=(null==e?void 0:e.details)||i.hls.latestLevelDetails)?void 0:t.live),O=i.hls.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(_=v-1;_>f;_--){var N=L[_].maxBitrate,B=!L[_].details||M;if((F=i.getTimeToLoadFrag(D,x,d*N,B))<Math.min(k,d+D))break}if(!(F>=C||F>10*d)){A?i.bwEstimator.sample(h-Math.min(E,S),c.loaded):i.bwEstimator.sampleTTFB(h);var U=L[_].maxBitrate;i.getBwEstimate()*O>U&&i.resetEstimator(U);var G=i.findBestLevel(U,f,_,0,k,1,1);G>-1&&(_=G),i.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(k.toFixed(3)," s\n Estimated load time for current fragment: ").concat(C.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(b)?0|b:"Unknown"," bps\n New BW estimate: ").concat(0|i.getBwEstimate()," bps\n Switching to level ").concat(_," @ ").concat(0|U," bps")),s.nextLoadLevel=s.nextAutoLevel=_,i.clearTimer();var V=function(){if(i.clearTimer(),i.fragCurrent===n&&i.hls.loadLevel===_&&_>0){var e=i.getStarvationDelay();if(i.warn("Aborting inflight request ".concat(_>0?"and switching down":"","\n Fragment duration: ").concat(n.duration.toFixed(3)," s\n Time to underbuffer: ").concat(e.toFixed(3)," s")),n.abortRequests(),i.fragCurrent=i.partCurrent=null,_>f){var t=i.findBestLevel(i.hls.levels[f].bitrate,f,_,0,e,1,1);-1===t&&(t=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=t,i.resetEstimator(i.hls.levels[t].bitrate)}}};m||C>2*F?V():i.timer=self.setInterval(V,1e3*F),s.trigger(ee.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:c})}}}}}}}},i.hls=e,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}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 i=t.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r: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 i=t.frag,r=this.fragCurrent,n=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var a=performance.now(),s=n?n.stats:i.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,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var i=this.hls.config,r=t.stats.loading,n=r.end-r.first;X(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var i=t.frag,r=t.part,n=r?r.stats:i.stats;if(i.type===ae&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var a=r?r.duration:i.duration,s=this.hls.levels[i.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(i.bitrateTest){var u={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(ee.FRAG_BUFFERED,u),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}},{key:"onFragBuffered",value:function(e,t){var i=t.frag,r=t.part,n=null!=r&&r.stats.loaded?r.stats:i.stats;if(!n.aborted&&!this.ignoreFragment(i)){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(),i.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,i=e.minAutoLevel,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(r,i,t,0,n,1,1);if(a>-1)return a;var s=this.hls.firstLevel,o=Math.min(Math.max(s,i),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(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},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,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,n=i.config,a=i.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,r,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,r,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=i.levels[a],m=i.loadLevelObj;return m&&(null==g?void 0:g.bitrate)<m.bitrate?a:i.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=e.media;if(!t)return 1/0;var i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}},{key:"getBwEstimate",value:function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}},{key:"findBestLevel",value:function(e,t,i,r,n,a,s){var o,l=this,u=r+n,c=this.lastLoadedFragLevel,d=-1===c?this.hls.firstLevel:c,h=this.fragCurrent,f=this.partCurrent,v=this.hls,g=v.levels,m=v.allAudioTracks,p=v.loadLevel,y=v.config;if(1===g.length)return 0;var E,T=g[d],k=!(null==(o=this.hls.latestLevelDetails)||!o.live),S=-1===p||-1===c,A="SDR",b=(null==T?void 0:T.frameRate)||0,L=y.audioPreference,I=y.videoPreference,R=this.audioTracksByGroup||(this.audioTracksByGroup=Wt(m)),w=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;var P=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce(function(e,i,r){if(!i.codecSet)return e;var n=i.audioGroups,a=e[i.codecSet];a||(e[i.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,i.bitrate);var s=Math.min(i.height,i.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,i.frameRate),a.minIndex=Math.min(a.minIndex,r),a.maxScore=Math.max(a.maxScore,i.score),a.fragmentError+=i.fragmentError,a.videoRanges[i.videoRange]=(a.videoRanges[i.videoRange]||0)+1,n&&n.forEach(function(e){if(e){var i=t.groups[e];i&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+i.channels[e]}))}}),e},{})}(g,R,t,i)),D=function(e,t,i,r,n){for(var a=Object.keys(e),s=null==r?void 0:r.channels,o=null==r?void 0:r.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,m=0,p=[],y=Ht(t,n),E=y.preferHDR,T=y.allowedVideoRanges,k=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),T.filter(function(e){return t.videoRanges[e]>0}).length>0&&(d=!0)},S=a.length;S--;)k();h=X(h)?h:0,f=X(f)?f:0;var A=Math.max(1080,h),b=Math.max(30,f);v=X(v)?v:i,i=Math.max(v,i),d||(t=void 0);var L=a.length>1;return{codecSet:a.reduce(function(t,r){var n=e[r];if(r===t)return t;if(p=d?T.filter(function(e){return n.videoRanges[e]>0}):[],L){if(n.minBitrate>i)return jt(r,"min bitrate of ".concat(n.minBitrate," > current estimate of ").concat(i)),t;if(!n.hasDefaultAudio)return jt(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return jt(r,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!n.channels[s])return jt(r,"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(r,"no renditions with stereo sound found"),t;if(n.minHeight>A)return jt(r,"min resolution of ".concat(n.minHeight," > maximum of ").concat(A)),t;if(n.minFramerate>b)return jt(r,"min framerate of ".concat(n.minFramerate," > maximum of ").concat(b)),t;if(!p.some(function(e){return n.videoRanges[e]>0}))return jt(r,"no variants with VIDEO-RANGE of ".concat(Kt(p)," found")),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return jt(r,'video codec preference "'.concat(l,'" not found')),t;if(n.maxScore<m)return jt(r,"max score of ".concat(n.maxScore," < selected max of ").concat(m)),t}return t&&(yt(r)>=yt(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,m=n.maxScore,r)},void 0),videoRanges:p,preferHDR:E,minFramerate:f,minBitrate:v,minIndex:g}}(P,A,e,L,I),C=D.codecSet,_=D.videoRanges,x=D.minFramerate,M=D.minBitrate,O=D.minIndex,F=D.preferHDR;w=O,E=C,A=F?_[_.length-1]:_[0],b=x,e=Math.max(e,M),this.log("picked start tier ".concat(Kt(D)))}else E=null==T?void 0:T.codecSet,A=null==T?void 0:T.videoRange;for(var N,B,U=f?f.duration:h?h.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,V=[],H=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,i,r,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,i){if(i){var r=t.groups[i];if(!r)throw new Error("Audio track group ".concat(i," not found"));Object.keys(r.channels).forEach(function(t){e[t]=(e[t]||0)+r.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(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(n,8e6))||!!d&&X(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,R,A,b,e,L)?(t.supportedPromise=Dt(t,R,h,l.supportedCache),t.supportedPromise.then(function(e){if(l.hls){t.supportedResult=e;var i=l.hls.levels,r=i.indexOf(t);e.error?l.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(r," ").concat(Kt(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&l.log("MediaCapabilities decodingInfo for level ".concat(r," not smooth or powerEfficient: ").concat(Kt(e))):(l.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(r," ").concat(Kt(e))),r>-1&&i.length>1&&(l.log("Removing unsupported level ".concat(r)),l.hls.removeLevel(r),-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||A&&t.videoRange!==A||o&&b>t.frameRate||!o&&b>0&&b<t.frameRate||null!=(N=t.supportedResult)&&null!=(N=N.decodingInfoResults)&&N.some(function(e){return!1===e.smooth}))&&(!S||K!==w))return V.push(K),0;var v,m=t.details,T=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||U;v=o?s*e:a*e;var I=U&&r>=2*U&&0===n?t.averageBitrate:t.maxBitrate,P=l.getTimeToLoadFrag(G,v,I*T,void 0===m);if(v>=I&&(K===c||0===t.loadError&&0===t.fragmentError)&&(P<=G||!X(P)||k&&!l.bitrateTestDelay||P<u)){var D=l.forcedAutoLevel;return K===p||-1!==D&&D===p||(V.length&&l.trace("Skipped level(s) ".concat(V.join(",")," of ").concat(i,' max with CODECS and VIDEO-RANGE:"').concat(g[V[0]].codecs,'" ').concat(g[V[0]].videoRange,'; not compatible with "').concat(E,'" ').concat(A)),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(T.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(p))),S&&(l.firstSelection=K),{v:K}}},K=i;K>=t;K--)if(0!==(B=H())&&B)return B.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){var t=this.hls,i=t.maxAutoLevel,r=t.minAutoLevel;return Math.min(Math.max(e,r),i)}}])}(ve),Zt=function(e,t){for(var i=0,r=e.length-1,n=null,a=null;i<=r;){var s=t(a=e[n=(i+r)/2|0]);if(s>0)i=n+1;else{if(!(s<0))return a;r=n-1}}return null};function ei(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=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-i;s>0&&s<15e-7&&(i+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===ti(i,r,a)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var r=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},i);return e.start<=r}return!1}(a,e,Math.min(n,r))))return a;var o=Zt(t,ti.bind(null,i,r));return!o||o===e&&a?a:o}function ti(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(i.start<=e&&i.start+i.duration>e)return 0;var r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function ii(e,t,i){var r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function ri(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){var r,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:(r=e,e.end<=i?1:e.start>i?-1:0)}),r||null}return null}function ni(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 ai(e){return e.details.startsWith("key")}function si(e){return ai(e)&&!!e.frag&&!e.frag.decryptdata}function oi(e,t){var i=ni(t);return e.default["".concat(i?"timeout":"error","Retry")]}function li(e,t){var i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function ui(e){return fe(fe({},e),{errorRetry:null,timeoutRetry:null})}function ci(e,t,i,r){if(!e)return!1;var n=null==r?void 0:r.code,a=t<e.maxNumRetry&&(function(e){return di(e)||!!e&&(e<400||e>499)}(n)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,a):a}function di(e){return 0===e&&!1===navigator.onLine}var hi=0,fi=2,vi=3,gi=5,mi=0,pi=1,yi=2,Ei=4,Ti=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["error-controller",e.logger])).hls=void 0,i.playlistError=0,i.hls=e,i.registerListeners(),i}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,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}},{key:"variantHasKey",value:function(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;var r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(function(e){return r.indexOf(e.groupId)>=0}).some(function(e){var i;return null==(i=e.details)?void 0:i.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 i;if(!t.fatal){var r=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!=(i=t.frag)&&i.gap)return void(t.errorAction=ki());case Z.FRAG_GAP:case Z.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=fi);case Z.LEVEL_EMPTY_ERROR:case Z.LEVEL_PARSING_ERROR:var a,s=t.parent===ae?t.level:r.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=r.loadLevelObj;if(o&&(n.type===re&&o.hasAudioGroup(n.groupId)||n.type===ne&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=fi,void(t.errorAction.flags=pi)}return;case Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:fi,flags:yi});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:fi,flags:Ei});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:r.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=ki())}t.type===J.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ki())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var i=oi(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(ci(i,r,ni(e),e.response))return{action:gi,flags:mi,retryConfig:i,retryCount:r};var n=this.getLevelSwitchAction(e,t);return i&&(n.retryConfig=i,n.retryCount=r),n}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=oi(ai(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(r&&(e.details!==Z.FRAG_GAP&&r.fragmentError++,!si(e)&&ci(o,l,ni(e),e.response)))return{action:gi,flags:mi,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,i);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var i=this.hls;null==t&&(t=i.loadLevel);var r=this.hls.levels[t];if(r){var n,a,s=e.details;r.loadError++,s===Z.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,u=i.loadLevel,c=i.minAutoLevel,d=i.maxAutoLevel;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);for(var h,f,v,g=null==(n=e.frag)?void 0:n.type,m=(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 r.audioCodec!==t}),p="video"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR)&&l.some(function(e){var t=e.codecSet,i=e.audioCodec;return r.codecSet!==t&&r.audioCodec===i}),y=null!=(a=e.context)?a:{},E=y.type,T=y.groupId,k=function(){var t=(S+u)%l.length;if(t!==u&&t>=c&&t<=d&&0===l[t].loadError){var i=l[t];if(s===Z.FRAG_GAP&&g===ae&&e.frag){var n=l[t].details;if(n){var a=ei(e.frag,n.fragments,e.frag.start);if(null!=a&&a.gap)return 0}}else{if(E===re&&i.hasAudioGroup(T)||E===ne&&i.hasSubtitleGroup(T))return 0;if(g===se&&null!=(h=r.audioGroups)&&h.some(function(e){return i.hasAudioGroup(e)})||g===oe&&null!=(f=r.subtitleGroups)&&f.some(function(e){return i.hasSubtitleGroup(e)})||m&&r.audioCodec===i.audioCodec||p&&r.codecSet===i.codecSet||!m&&r.codecSet!==i.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(v=k())||1!==v););if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:fi,flags:mi,nextAutoLevel:o}}return{action:fi,flags:pi}}},{key:"onErrorOut",value:function(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case hi:break;case fi: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,i=e.errorAction;if(i){var r=i.flags,n=i.nextAutoLevel;switch(r){case mi:this.switchLevel(e,n);break;case yi:var a=this.getVariantLevelIndex(e.frag),s=t.levels[a],o=null==s?void 0:s.attrs["HDCP-LEVEL"];if(i.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=xt[xt.indexOf(o)-1],i.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'));break}case Ei: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(be(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)i.resolved=!0;else if(v&&v.type!==ae){var g=v.decryptdata;g&&!l.matches(g)&&(i.resolved=!0)}}}i.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 i=It(e.mimeType),r=this.hls.levels,n=r.length;n--;)r[n]["".concat(e.sourceBufferName,"Codec")]===i&&(this.log("Removing level ".concat(n," for ").concat(e.details,' ("').concat(i,'" not supported)')),this.hls.removeLevel(n))}}])}(ve);function ki(e){var t={action:hi,flags:mi};return e&&(t.resolved=!0),t}var Si="NOT_LOADED",Ai="APPENDING",bi="PARTIAL",Li="OK",Ii=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 i=this.activePartLists[t];if(i)for(var r=i.length;r--;){var n=i[r];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,i){for(var r=this.fragments,n=Object.keys(r),a=n.length;a--;){var s=r[n[a]];if((null==s?void 0:s.body.type)===t&&(!i||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,i,r,n){var a=this;this.timeRanges&&(this.timeRanges[e]=t);var s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(r){var o=a.fragments[r];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 i=!a.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&a.removeFragment(o.body),i}):a.removeFragment(o.body))}else o.body.type===i&&a.removeFragment(o.body)})}},{key:"detectPartialFragments",value:function(e){var t=this,i=this.timeRanges;if(i&&"initSegment"!==e.frag.sn){var r=e.frag,n=wi(r),a=this.fragments[n];if(!(!a||a.buffered&&r.gap)){var s=!r.relurl;Object.keys(i).forEach(function(n){var o=r.elementaryStreams[n];if(o){var l=i[n],u=s||!0===o.partial;a.range[n]=t.getBufferedTimes(r,e.part,u,l)}}),a.loaded=null,Object.keys(a.range).length?(this.bufferedEnd(a,r),Ri(a)||this.removeParts(r.sn-1,r.type)):this.removeFragment(a.body)}}}},{key:"bufferedEnd",value:function(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}},{key:"removeParts",value:function(e,t){var i=this.activePartLists[t];i&&(this.activePartLists[t]=Pi(i,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var i=wi(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}},{key:"getBufferedTimes",value:function(e,t,i,r){for(var n={time:[],partial:i},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<r.length;u++){var c=r.start(u)-this.bufferPadding,d=r.end(u)+this.bufferPadding;if(l>=c&&o<=d){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(s,r.end(u))});break}if(a<d&&s>c){var h=Math.max(a,r.start(u)),f=Math.min(s,r.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,i,r,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&Ri(u)&&(i=u.body.start-s,r=u.body.end+s,e>=i&&e<=r&&(t=Math.min(e-i,r-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||Ri(t))}},{key:"getState",value:function(e){var t=wi(e),i=this.fragments[t];return i?i.buffered?Ri(i)?bi:Li:Ai:Si}},{key:"isTimeBuffered",value:function(e,t,i){for(var r,n,a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)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 i=t.frag,r=t.part?null:t,n=wi(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var i=t.frag,r=t.part,n=t.timeRanges,a=t.type;if("initSegment"!==i.sn){var s=i.type;if(r){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(r)}this.timeRanges=n;var l=n[a];this.detectEvictedFragments(a,l,s,r)}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=wi(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,i=Object.keys(t);if(!e)return i.length>0;for(var r=i.length;r--;){var n=t[i[r]];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,i,r,n){var a=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=wi(e);e.clearElementaryStreamInfo();var i=this.activePartLists[e.type];if(i){var r=e.sn;this.activePartLists[e.type]=Pi(i,function(e){return e.fragment.sn!==r})}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 Ri(e){var t,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(r=e.range.audiovideo)&&r.partial)}function wi(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function Pi(e,t){return e.filter(function(e){var i=t(e);return i||e.clearElementaryStreamInfo(),i})}var Di=0,Ci=1,_i=function(){return o(function e(t,i,r){a(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=i,this.aesMode=r},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case Di:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ci: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 xi=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),i=new Uint32Array(4),r=0;r<4;r++)i[r]=t.getUint32(4*r);return i}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],s=i[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 m=v^v<<1^v<<2^v<<3^v<<4;m=m>>>8^255&m^99,e[f]=m,t[m]=f;var p=h[f],y=h[p],E=h[y],T=257*h[m]^16843008*m;r[f]=T<<24|T>>>8,n[f]=T<<16|T>>>16,a[f]=T<<8|T>>>24,s[f]=T,T=16843009*E^65537*y^257*p^16843008*f,l[m]=T<<24|T>>>8,u[m]=T<<16|T>>>16,c[m]=T<<8|T>>>24,d[m]=T,f?(f=p^h[h[h[E^p]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;r<t.length&&i;)i=t[r]===this.key[r],r++;if(!i){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],m=v[1],p=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]]^m[h[l>>>16&255]]^p[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,i){for(var r,n,a,s,o,l,u,c,d,h,f,v,g,m,p=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,k=T[0],S=T[1],A=T[2],b=T[3],L=this.uint8ArrayToUint32Array_(i),I=L[0],R=L[1],w=L[2],P=L[3],D=new Int32Array(e),C=new Int32Array(D.length),_=this.networkToHostOrderSwap;t<D.length;){for(d=_(D[t]),h=_(D[t+1]),f=_(D[t+2]),v=_(D[t+3]),o=d^y[0],l=v^y[1],u=f^y[2],c=h^y[3],g=4,m=1;m<p;m++)r=k[o>>>24]^S[l>>16&255]^A[u>>8&255]^b[255&c]^y[g],n=k[l>>>24]^S[u>>16&255]^A[c>>8&255]^b[255&o]^y[g+1],a=k[u>>>24]^S[c>>16&255]^A[o>>8&255]^b[255&l]^y[g+2],s=k[c>>>24]^S[o>>16&255]^A[l>>8&255]^b[255&u]^y[g+3],o=r,l=n,u=a,c=s,g+=4;r=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],C[t]=_(r^I),C[t+1]=_(s^R),C[t+2]=_(a^w),C[t+3]=_(n^P),I=d,R=h,w=f,P=v,t+=4}return C.buffer}}])}(),Mi=function(){return o(function e(t,i,r){a(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=i,this.aesMode=r},[{key:"expandKey",value:function(){var e=function(e){switch(e){case Di:return"AES-CBC";case Ci: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 Oi=function(){return o(function e(t){var i=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).removePKCS7Padding,r=void 0===i||i;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=r,r)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 i,r,n,a=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(r=(i=a).byteLength,(n=r&&new DataView(i.buffer).getUint8(r-1))?i.slice(0,r-n):i):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,i,r){var n=this;return this.useSoftware?new Promise(function(a,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);n.softwareDecrypt(o,t,i,r);var l=n.flush();l?a(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}},{key:"softwareDecrypt",value:function(e,t,i,r){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(r!==Di||16!==t.byteLength)return Te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=rt(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(i=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new xi),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,i,r){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Mi(this.subtle,t,r)}return this.fastAesKey.expandKey().then(function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new _i(n.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return Te.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),n.onWebCryptoError(e,t,i,r)})}},{key:"onWebCryptoError",value:function(e,t,i,r){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);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,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(Te.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),Fi=Math.pow(2,17),Ni=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 i=this,r=e.url;if(!r)return Promise.reject(new Gi({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(r?"part list":"url")),networkDetails:null}));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){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void l(Ui(e));e.gap=!1}var u=i.loader=a?new a(n):new s(n),c=Bi(e);e.loader=u;var d=ui(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Fi};e.stats=u.stats;var f={onSuccess:function(t,r,n,a){i.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){i.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:fe({url:r,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:a,stats:s}))},onAbort:function(t,r,n){i.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,r,n){i.resetLoader(e,u),l(new Gi({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(i,r,n,a){return t({frag:e,part:null,payload:n,networkDetails:a})}),u.load(c,h,f)})}},{key:"loadPart",value:function(e,t,i){var r=this;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||t.gap)l(Ui(e,t));else{var u=r.loader=a?new a(n):new s(n),c=Bi(e,t);e.loader=u;var d=ui(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Fi};t.stats=u.stats,u.load(c,h,{onSuccess:function(n,a,s,l){r.resetLoader(e,u),r.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:n.data,networkDetails:l};i(c),o(c)},onError:function(i,n,a,s){r.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:fe({url:c.url,data:void 0},i),error:new Error("HTTP Error ".concat(i.code," ").concat(i.text)),networkDetails:a,stats:s}))},onAbort:function(i,n,a){e.stats.aborted=t.stats.aborted,r.resetLoader(e,u),l(new Gi({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:function(i,n,a){r.resetLoader(e,u),l(new Gi({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:i}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(i.loaded/n),a),o=(a-s)*Math.round(i.loaded/s);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,u=r.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 Bi(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=i||e,n={frag:e,part:i,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,s=r.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 Ui(e,t){var i=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),r={type:J.MEDIA_ERROR,details:Z.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Gi(r)}var Gi=function(e){function t(e){var i;return a(this,t),(i=n(this,t,[e.error.message])).data=void 0,i.data=e,i}return d(t,e),o(t)}(L(Error)),Vi=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[e,i]))._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}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),Hi=o(function e(t,i,r){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=i,this.id=r,this.size=n,this.part=s,this.partial=o});var Ki={length:0,start:function(){return 0},end:function(){return 0}},ji=function(){function e(){a(this,e)}return o(e,null,[{key:"isBuffered",value:function(t,i){if(t)for(var r=e.getBuffered(t),n=r.length;n--;)if(i>=r.start(n)&&i<=r.end(n))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var i=e.getBuffered(t);return e.timeRangesToArray(i)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}},{key:"bufferInfo",value:function(t,i,r){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,i){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var r=-1,n=[];if(i)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(r=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<i?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===r&&t>=f&&t<=v&&(r=h),t+i>=f&&t<v)c=f,u=(d=v)-t;else if(t+i<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:r}}},{key:"getBuffered",value:function(e){try{return e.buffered||Ki}catch(e){return Te.log("failed to get media.buffered",e),Ki}}}])}(),Wi=/\{\$([a-zA-Z0-9-_]+)\}/g;function qi(e){return Wi.test(e)}function Yi(e,t){if(null!==e.variableList||e.hasVariableRefs){var i=e.variableList;return t.replace(Wi,function(t){var r=t.substring(2,t.length-1),n=null==i?void 0:i[r];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(r,'"'))),t):n})}return t}function zi(e,t,i){var r,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{var s=new self.URL(i).searchParams;if(!s.has(r))throw new Error('"'.concat(r,'" does not match any query parameter in URI: "').concat(i,'"'));n=s.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(t.message)))}}else r=t.NAME,n=t.VALUE;r in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(r,'"'))):a[r]=n||""}function Xi(e,t,i){var r=t.IMPORT;if(i&&r in i){var n=e.variableList;n||(e.variableList=n={}),n[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(r,'"')))}var Qi=/^(\d+)x(\d+)$/,$i=/(.+?)=(".*?"|.*?)(?:,|$)/g,Ji=function(){return o(function e(t,i){a(this,e),"string"==typeof t&&(t=e.parseAttrList(t,i)),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 i=new Uint8Array(t.length/2),r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(2*r,2*r+2),16);return i}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 i=this[e];return i?parseFloat(i):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var i=this[e];return(i?i.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=Qi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var i,r={};for($i.lastIndex=0;null!==(i=$i.exec(e));){var n=i[1].trim(),a=i[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=Yi(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":Te.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}r[n]=a}return r}}])}();function Zi(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function er(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var tr=function(){return o(function e(t,i){var r,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==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(r=null==i?void 0:i.tagOrder)?r:n,i){var s=i.attr;for(var o in s)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==s[o]){Te.warn('DATERANGE tag attribute: "'.concat(o,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=o;break}t=de(new Ji({}),s,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var l=(null==i?void 0:i.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?(Te.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)}}])}(),ir=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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>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 i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}},{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 i=e.length;i--;)if(e[i].index>t)return e[i].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 rr(e,t){return e.length===t.length&&!e.some(function(e,i){return e!==t[i]})}function nr(e,t){return!e&&!t||!(!e||!t)&&rr(e,t)}function ar(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function sr(e){switch(e){case"AES-128":case"AES-256":return Di;case"AES-256-CTR":return Ci;default:throw new Error("invalid full segment method ".concat(e))}}function or(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function lr(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function ur(e){var t=function(e,t,i){var r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function cr(e){var t,i,r=e.split(":"),n=null;if("data"===r[0]&&2===r.length){var a=r[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=or(l)):(t=lr(l).subarray(0,16),(i=new Uint8Array(16)).set(t,16-t.length),n=i)}}return n}var dr="undefined"!=typeof self?self:void 0,hr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fr="org.w3.clearkey",vr="com.apple.streamingkeydelivery",gr="com.microsoft.playready",mr="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function pr(e){switch(e){case vr:return hr.FAIRPLAY;case gr:return hr.PLAYREADY;case mr:return hr.WIDEVINE;case fr:return hr.CLEARKEY}}function yr(e){switch(e){case hr.FAIRPLAY:return vr;case hr.PLAYREADY:return gr;case hr.WIDEVINE:return mr;case hr.CLEARKEY:return fr}}function Er(e){var t=e.drmSystems,i=e.widevineLicenseUrl,r=t?[hr.FAIRPLAY,hr.WIDEVINE,hr.PLAYREADY,hr.CLEARKEY].filter(function(e){return!!t[e]}):[];return!r[hr.WIDEVINE]&&i&&r.push(hr.WIDEVINE),r}var Tr,kr=null!=dr&&null!=(Tr=dr.navigator)&&Tr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Sr(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){var a=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(a){var s=or(a).subarray(0,16);return ur(s),s}}return null}var Ar={},br=function(){function e(t,i,r){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=i,this.keyFormat=r,this.keyFormatVersions=n,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ar(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&&rr(e.keyFormatVersions,this.keyFormatVersions)&&nr(e.iv,this.iv)&&nr(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(ar(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case vr:case mr:case gr:case fr:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,i){if(!this.encrypted||!this.uri)return null;if(ar(this.method)){var r=this.iv;return r||("number"!=typeof t&&(Te.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),r=function(e){for(var t=new Uint8Array(16),i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){var n=Ar[this.uri];if(n&&!rr(this.keyId,n)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var a,s=cr(this.uri);if(s)switch(this.keyFormat){case mr:if(this.pssh=s,!this.keyId){var o=function(e){var t=[];if(e instanceof ArrayBuffer)for(var i=e.byteLength,r=0;r+32<i;){var n=ct(new DataView(e,r));t.push(n),r+=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=Lr(i));break;case gr: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=Sr(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[mr];if(t)return t.keyId;return null}(i),a||(a=Lr(i))||(a=Ar[this.uri]),a&&(this.keyId=a,e.setKeyIdForUri(this.uri,a)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){Ar={}}},{key:"setKeyIdForUri",value:function(e,t){Ar[e]=t}},{key:"addKeyIdForUri",value:function(e){var t=Object.keys(Ar).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Ar[e]=i,i}}])}();function Lr(e){var t=null==e?void 0:e[gr];if(t){var i=cr(t.uri);if(i)return Sr(i)}return null}var Ir=/#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,Rr=/#EXT-X-MEDIA:(.*)/g,wr=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Dr=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("|")),Cr=function(){function e(){a(this,e)}return o(e,null,[{key:"findGroup",value:function(e,t){for(var i=0;i<e.length;i++){var r=e[i];if(r.id===t)return r}}},{key:"resolve",value:function(e,t){return Pe.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return wr.test(e)}},{key:"parseMasterPlaylist",value:function(t,i){var r,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:qi(t)},a=[];if(Ir.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(r=Ir.exec(t));)if(r[1]){var s,o=new Ji(r[1],n),l=Yi(n,r[2]),u={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,i)},c=o.decimalResolution("RESOLUTION");c&&(u.width=c.width,u.height=c.height),Fr(o.CODECS,u);var d=o["SUPPLEMENTAL-CODECS"];d&&(u.supplemental={},Fr(d,u.supplemental)),null!=(s=u.unknownCodecs)&&s.length||a.push(u),n.levels.push(u)}else if(r[3]){var h=r[3],f=r[4];switch(h){case"SESSION-DATA":var v=new Ji(f,n),g=v["DATA-ID"];g&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[g]=v);break;case"SESSION-KEY":var m=Mr(f,i,n);m.encrypted&&m.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(m)):Te.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(f,'"'));break;case"DEFINE":zi(n,new Ji(f,n),i);break;case"CONTENT-STEERING":var p=new Ji(f,n);n.contentSteering={uri:e.resolve(p["SERVER-URI"],i),pathwayId:p["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Or(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,i,r){var n,a={},s=r.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(Rr.lastIndex=0;null!==(n=Rr.exec(t));){var u=new Ji(n[1],r),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,m=u.CHARACTERISTICS,p=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,i):""};if(v&&(y.assocLang=v),g&&(y.channels=g),m&&(y.characteristics=m),p&&(y.instreamId=p),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Nr(y,E,"audioCodec"),Nr(y,E,"textCodec")}h.push(y)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,i,r,n,a){var s,o,l,u,c,d={url:t},h=new ir(t),f=h.fragments,v=[],g=null,m=0,p=0,y=0,E=0,T=0,k=null,S=new Fe(r,d),A=-1,b=!1,L=null;if(Pr.lastIndex=0,h.m3u8=e,h.hasVariableRefs=qi(e),"#EXTM3U"!==(null==(s=Pr.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=Pr.exec(e));){b&&(b=!1,(S=new Fe(r,d)).playlistOffset=y,S.setStart(y),S.sn=m,S.cc=E,T&&(S.bitrate=T),S.level=i,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&&Gr(S,u,h),S.sn=m,S.level=i,S.cc=E,f.push(S);var w=(" "+o[3]).slice(1);S.relurl=Yi(h,w),Br(S,k,v),k=S,y+=S.duration,m++,p=0,b=!0}}else{if(!(o=o[0].match(Dr))){Te.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),D=(" "+o[l+1]).slice(1),C=o[l+2]?(" "+o[l+2]).slice(1):null;switch(P){case"BYTERANGE":k?S.setByteRange(D,k):S.setByteRange(D);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=D,S.tagList.push(["PROGRAM-DATE-TIME",D]),-1===A&&(A=f.length);break;case"PLAYLIST-TYPE":h.type&&Vr(h,P,o),h.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Vr(h,P,o):f.length>0&&Hr(h,P,o),m=h.startSN=parseInt(D);break;case"SKIP":h.skippedSegments&&Vr(h,P,o);var _=new Ji(D,h),x=_.decimalInteger("SKIPPED-SEGMENTS");if(X(x)){h.skippedSegments+=x;for(var M=x;M--;)f.push(null);m+=x}var O=_.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(O.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&Vr(h,P,o),h.targetduration=Math.max(parseInt(D),1);break;case"VERSION":null!==h.version&&Vr(h,P,o),h.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Vr(h,P,o),h.live=!1;break;case"#":(D||C)&&S.tagList.push(C?[D,C]:[D]);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,D]),T=1e3*parseInt(D),X(T)?S.bitrate=T:T=0;break;case"DATERANGE":var F=new Ji(D,h),N=new tr(F,h.dateRanges[F.ID],h.dateRangeTagCount);h.dateRangeTagCount++,N.isValid||h.skippedSegments?h.dateRanges[N.id]=N:Te.warn('Ignoring invalid DATERANGE tag: "'.concat(D,'"')),S.tagList.push(["EXT-X-DATERANGE",D]);break;case"DEFINE":var B=new Ji(D,h);"IMPORT"in B?Xi(h,B,a):zi(h,B,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?Vr(h,P,o):f.length>0&&Hr(h,P,o),h.startCC=E=parseInt(D);break;case"KEY":var U=Mr(D,t,h);if(U.isSupported()){if("NONE"===U.method){u=void 0;break}u||(u={});var G=u[U.keyFormat];null!=G&&G.matches(U)||(G&&(u=de({},u)),u[U.keyFormat]=U)}else Te.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(D,'"'));break;case"START":h.startTimeOffset=Or(D);break;case"MAP":var V=new Ji(D,h);if(S.duration){var H=new Fe(r,d);Ur(H,V,i,u),g=H,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;Ur(S,V,i,u),g=S,b=!0}g.cc=E;break;case"SERVER-CONTROL":c&&Vr(h,P,o),c=new Ji(D),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&&Vr(h,P,o);var W=new Ji(D);h.partTarget=W.decimalFloatingPoint("PART-TARGET");break;case"PART":var q=h.partList;q||(q=h.partList=[]);var Y=p>0?q[q.length-1]:void 0,z=p++,Q=new Ji(D,h),$=new Ne(Q,S,d,z,Y);q.push($),S.duration+=$.duration;break;case"PRELOAD-HINT":var J=new Ji(D,h);h.preloadHint=J;break;case"RENDITION-REPORT":var Z=new Ji(D,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(Z);break;default:Te.warn("line parsed but not handled: ".concat(o))}}}k&&!k.relurl?(f.pop(),y-=k.duration,h.partList&&(h.fragmentHint=k)):h.partList&&(Br(S,k,v),S.cc=E,h.fragmentHint=S,u&&Gr(S,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var ee=f.length,te=f[0],ie=f[ee-1];if((y+=h.skippedSegments*h.targetduration)>0&&ee&&ie){h.averagetargetduration=y/ee;var re=ie.sn;h.endSN="initSegment"!==re?re:0,h.live||(ie.endList=!0),A>0&&(!function(e,t){for(var i=e[t],r=t;r--;){var n=e[r];if(!n)return;n.programDateTime=i.programDateTime-1e3*n.duration,i=n}}(f,A),te&&v.unshift(te))}return h.fragmentHint&&(y+=h.fragmentHint.duration),h.totalduration=y,v.length&&h.dateRangeTagCount&&te&&_r(v,h),h.endCC=E,h}}])}();function _r(e,t){var i=e.length;if(!i){if(!t.hasProgramDateTime)return;var r=t.fragments[t.fragments.length-1];e.push(r),i++}for(var n=e[i-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=i;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=xr(t,u,e,c,a);if(-1!==h){l.tagAnchor=t.fragments[h].ref;break}}}}function xr(e,t,i,r,n){var a=i[r];if(a){var s,o=a.programDateTime;if(t>=o||0===r)if(t<=o+1e3*(((null==(s=i[r+1])?void 0:s.start)||n)-a.start)){var l=i[r].sn-e.startSN;if(l<0)return-1;var u=e.fragments;if(u.length>i.length)for(var c=(i[r+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 Mr(e,t,i){var r,n,a=new Ji(e,i),s=null!=(r=a.METHOD)?r:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&Te.error("Invalid IV: ".concat(a.IV));var d=o?Cr.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new br(s,d,c,h,l,a.KEYID)}function Or(e){var t=new Ji(e).decimalFloatingPoint("TIME-OFFSET");return X(t)?t:null}function Fr(e,t){var i=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text"].forEach(function(e){var r=i.filter(function(t){return ft(t,e)});r.length&&(t["".concat(e,"Codec")]=r.map(function(e){return e.split("/")[0]}).join(","),i=i.filter(function(e){return-1===r.indexOf(e)}))}),t.unknownCodecs=i}function Nr(e,t,i){var r=t[i];r&&(e[i]=r)}function Br(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Ur(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function Gr(e,t,i){e.levelkeys=t;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||r.push(e)}function Vr(e,t,i){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(i[0],")"))}function Hr(e,t,i){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(i[0],")"))}function Kr(e,t){var i=t.startPTS;if(X(i)){var r,n=0;t.sn>e.sn?(n=i-e.start,r=e):(n=e.start-i,r=t),r.duration!==n&&r.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 jr(e,t,i,r,n,a,s){r-i<=0&&(s.warn("Fragment should have a positive duration",t),r=i+t.duration,a=n+t.duration);var o=i,l=r,u=t.startPTS,c=t.endPTS;if(X(u)){var d=Math.abs(u-i);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(i,u),i=Math.min(i,u),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,l=Math.min(r,c),r=Math.max(r,c),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var h=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=n,t.endPTS=r,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,m=e.fragments;for(m[g]=t,f=g;f>0;f--)Kr(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Kr(m[f],m[f+1]);return e.fragmentHint&&Kr(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function Wr(e,t,i){if(e!==t){for(var r,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,i){for(var r=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(r?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(r&&!d&&c&&(d=t.fragments[u]=c),c&&d){i(c,d,u,o);var h=c.relurl,f=d.relurl;if(h&&en(h,f))return void(t.playlistParsingError=qr("media sequence mismatch ".concat(d.sn,":"),e,t,c,d));if(c.cc!==d.cc)return void(t.playlistParsingError=qr("discontinuity sequence mismatch (".concat(c.cc,"!=").concat(d.cc,")"),e,t,c,d))}}}(e,t,function(e,i,a,s){if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){for(var o=e.cc-i.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}X(e.startPTS)&&X(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(r=i),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.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){i.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,i){var r=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 r;return Object.keys(r).forEach(function(e){var t=a[e],n=new tr(r[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):i.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(Kt(r[e].attr),'"'))}),a}(e.dateRanges,t,i));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&&Br(u[h],u[h-1],d);_r(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=Qr(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}!function(e,t,i){if(e&&t)for(var r=0,n=0,a=e.length;n<=a;n++){var s=e[n],o=t[n+r];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?i(s,o):r--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),r?jr(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):Yr(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 m=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=m),t.driftEndTime=g,t.driftEnd=m}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function qr(e,t,i,r,n){return new Error("".concat(e," ").concat(n.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(i.startSN,"\n").concat(i.m3u8))}function Yr(e,t){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,a=r>=0,s=0;if(a&&r<n.length)s=n[r].start;else if(a&&t.startSN===e.endSN+1)s=e.fragmentEnd;else if(a&&i)s=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;s=e.fragmentStart}zr(t,s)}function zr(e,t){if(t){for(var i=e.fragments,r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Xr(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,i=1e3*e.targetduration;if(e.updated){var r=e.fragments;if(r.length&&4*i>t){var n=1e3*r[r.length-1].duration;n<i&&(i=n)}}else i/=2;return Math.round(i)}function Qr(e,t,i){if(!e)return null;var r=e.fragments[t-e.startSN];return r||((r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function $r(e,t,i){return e?Jr(e.partList,t,i):null}function Jr(e,t,i){if(e)for(var r=e.length;r--;){var n=e[r];if(n.index===i&&n.fragment.sn===t)return n}return null}function Zr(e){e.forEach(function(e,t){var i;null==(i=e.details)||i.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 i=0,r=e.length;i<r;i++){var n;if((null==(n=e[i])?void 0:n.cc)===t)return e[i]}return null}function nn(e,t){var i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function an(e,t){for(var i=t.fragments,r=0,n=i.length;r<n;r++)nn(i[r],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 i=Math.min(t.endCC,e.endCC),r=rn(t.fragments,i),n=rn(e.fragments,i);if(r&&n)Te.log("Aligning playlist at start of dicontinuity sequence ".concat(i)),an(r.start-n.start,e)}}function on(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i=e.fragments,r=t.fragments;if(i.length&&r.length){var n,a,s=Math.min(t.endCC,e.endCC);t.startCC<s&&e.startCC<s&&(n=rn(r,s),a=rn(i,s)),n&&a||(a=rn(i,(n=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.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,i){un(e,t,i),e.addEventListener(t,i)}function un(e,t,i){e.removeEventListener(t,i)}var cn=function(e){for(var t="",i=e.length,r=0;r<i;r++)t+="[".concat(e.start(r).toFixed(3),"-").concat(e.end(r).toFixed(3),"]");return t},dn="STOPPED",hn="IDLE",fn="KEY_LOADING",vn="FRAG_LOADING",gn="FRAG_LOADING_WAITING_RETRY",mn="WAITING_TRACK",pn="PARSING",yn="PARSED",En="ENDED",Tn="ERROR",kn="WAITING_INIT_PTS",Sn="WAITING_LEVEL",An=function(e){function t(e,i,r,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,i=e.fragCurrent,r=e.media,n=e.mediaBuffer,a=e.state,s=r?r.currentTime:0,o=ji.bufferInfo(n||r,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(i){var c=t.maxFragLookUpTolerance,d=i.start-c,h=i.start+i.duration+c;if(u||h<o.start||d>o.end){var f=s>h;(s<d||f)&&(f&&i.loader&&(l.log("Cancelling fragment load for seek (sn: ".concat(i.sn,")")),i.abortRequests(),l.resetLoadingState()),l.fragPrevious=null)}}if(r&&(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 Ni(e.config),l.keyLoader=r,l.fragmentTracker=i,l.config=e.config,l.decrypter=new Oi(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 i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=ji.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>r&&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 ji.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 i=this.media=this.mediaBuffer=t.media;ln(i,"seeking",this.onMediaSeeking),ln(i,"ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===dn&&this.startLoad(r.startPosition)}},{key:"onMediaDetaching",value:function(e,t){var i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),un(r,"seeking",this.onMediaSeeking),un(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)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,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}},{key:"_loadFragForPlayback",value:function(e,t,i){var r=this;this._doFragLoad(e,t,i,function(e){var t=e.frag;if(r.fragContextChanged(t))return r.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(r.fragInfo(t,!1,e.part),") was dropped during download.")),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=r.state,i=e.frag;r.fragContextChanged(i)?(t===vn||!r.fragCurrent&&t===pn)&&(r.fragmentTracker.removeFragment(i),r.state=hn):("payload"in e&&(r.log("Loaded ".concat(i.type," sn: ").concat(i.sn," of ").concat(r.playlistLabel()," ").concat(i.level)),r.hls.trigger(ee.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}}).catch(function(t){r.state!==dn&&r.state!==Tn&&(r.warn("Frag error: ".concat((null==t?void 0:t.message)||t)),r.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,i=this.fragmentTracker;if(i.getState(e)===Ai){var r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),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))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===bi&&i.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 i={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(ee.BUFFER_FLUSHING,i)}}},{key:"_loadInitSegment",value:function(e,t){var i=this;this._doFragLoad(e,t).then(function(e){var t=null==e?void 0:e.frag;if(!t||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e}).then(function(e){var t=i.hls,r=e.frag,n=e.payload,a=r.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&ar(a.method)){var s=self.performance.now();return i.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,sr(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:r}),e}).then(function(n){var a=self.performance.now();return t.trigger(ee.FRAG_DECRYPTED,{frag:r,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,i.completeInitSegmentLoad(e)})}return i.completeInitSegmentLoad(e)}).catch(function(t){i.state!==dn&&i.state!==Tn&&(i.warn(t),i.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 i,r,n=e.tracks;if(n&&!t.encrypted&&(null!=(i=n.audio)&&i.encrypted||null!=(r=n.video)&&r.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 i=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(i?cn(ji.getBuffered(i)):"(detached)",")")),Oe(e)){var r;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==(r=this.levels)?void 0:r[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 i=e.frag,r=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some(function(e){return!e}),s=new Hi(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(s)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"_doFragLoad",value:function(e,t){var i,r=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!=(i=e.decryptdata)&&i.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(!r.fragContextChanged(e.frag))return r.hls.trigger(ee.KEY_LOADED,e),r.state===fn&&(r.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(i){return!i||r.fragContextChanged(i.frag)?null:r.doFragPartsLoad(e,v,t,a)}).catch(function(e){return r.handleFragLoadError(e)}):this.doFragPartsLoad(e,v,t,a).catch(function(e){return r.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,m=this.config.progressive&&e.type!==oe;return g=m&&o?o.then(function(t){return!t||r.fragContextChanged(t.frag)?null:r.fragmentLoader.load(e,a)}).catch(function(e){return r.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,m?a:void 0),o]).then(function(e){var t=p(e,1)[0];return!m&&a&&a(t),t}).catch(function(e){return r.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,i,r){var n=this;return new Promise(function(a,s){var o,l=[],u=null==(o=i.details)?void 0:o.partList,c=function(t){n.fragmentLoader.loadPart(e,t,r).then(function(r){l[t.index]=r;var s=r.part;n.hls.trigger(ee.FRAG_LOADED,r);var o=$r(i.details,e.sn,t.index+1)||Jr(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===pn){var i=t.frag,r=t.part,n=t.level,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&i.sn>s.endSN||this.shouldLoadParts(s,i.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(i.end.toFixed(2))),this.loadingParts=o),this.updateLevelTiming(i,r,n,e.partial)}else this.fragCurrent||this.state===dn||this.state===Tn||(this.state=hn)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i,r,n=e.partList[0];if(n.fragment.type===oe)return!1;if(t>=n.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0))if((this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,i=this.fragCurrent,r=e.level,n=e.sn,a=e.part;if(null==t||!t[r])return this.warn("Levels object was unset while buffering fragment ".concat(n," of ").concat(this.playlistLabel()," ").concat(r,". The current chunk will not be buffered.")),null;var s=t[r],o=s.details,l=a>-1?$r(o,n,a):null,u=l?l.fragment:Qr(o,n,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,i,r,n){if(this.state===pn){var a=e.data1,s=e.data2,o=a;if(s&&(o=rt(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:i,chunkMeta:r,offset:u,parent:t.type,data:o};if(this.hls.trigger(ee.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(ji.isBuffered(t,t.currentTime)){var i=t.currentTime,r=ji.bufferInfo(t,i,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var i,r=this.getLoadPosition();if(!X(r))return null;var n=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,n)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,i,r){var n=ji.bufferInfo(e,t,r);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,r);return ji.bufferInfo(e,t,s)}}return n}},{key:"getMaxBufferLength",value:function(e){var t,i=this.config;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)}},{key:"reduceMaxBufferLength",value:function(e,t){var i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return n>=r&&(i.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,i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}},{key:"getNextFragment",value:function(e,t){var i=t.fragments,r=i.length;if(!r)return null;var n=this.config,a=i[0].start,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: ".concat(r,", 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=i[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(i[g+1]||null,t)}return this.mapToInitFragWhenRequired(v)}},{key:"isLoopLoading",value:function(e,t){var i=this.fragmentTracker.getState(e);return(i===Li||i===bi&&!!e.gap)&&this.nextLoadPosition>t}},{key:"getNextFragmentLoopLoading",value:function(e,t,i,r,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&i.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==s&&i.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(r,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(bn(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(bn(this.config)&&e.type!==oe){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var n=r.event;if(n){if(n.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}var a=null==i?void 0:i.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,i){for(var r=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,r>-1&&i<l.start)break;var u=l.loaded;u?r=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn("Need buffer at ".concat(i," but next unloaded part starts at ").concat(l.start)),r=s),n=u}return r}},{key:"loadedEndOfParts",value:function(e,t){for(var i,r=e.length;r--;){if(!(i=e[r]).loaded)return!1;if(t>i.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(i.programDateTime)),r=function(e,t,i){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 r=0;r<e.length;++r){var n=e[r];if(ii(t,i,n))return n}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(r.sn)))}r||(r=ri(e,i.cc,i.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(r.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(r=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}},{key:"getFragmentAtPosition",value:function(e,t,i){var r,n,a=this.config,s=this.fragPrevious,o=i.fragments,l=i.endSN,u=i.fragmentHint,c=a.maxFragLookUpTolerance,d=i.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)?r=ei(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:c):r=o[o.length-1];if(r){var f=r.sn-i.startSN,v=this.fragmentTracker.getState(r);if((v===Li||v===bi&&r.gap)&&(s=r),s&&r.sn===s.sn&&(!h||d[0].fragment.sn>r.sn||!i.live))if(r.level===s.level){var g=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(g)!==Li?g:null}}return r}},{key:"alignPlaylists",value:function(e,t,i){var r=e.fragments.length;if(!r)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||Yr(e,t,!1))}(i,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(r)),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 i=this.startPosition;i<t&&(i=-1);var r=this.timelineOffset;if(-1===i){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;null!==a&&X(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log("Setting startPosition to ".concat(i," for start time offset ").concat(a," found in ").concat(n?"multivariant":"media"," playlist")),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge ".concat(i)),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}},{key:"getLoadPosition",value:function(){var e,t=this.media,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}},{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 i;if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.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===gi,g=f&&!o.resolved&&u===pi,m=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!v&&g&&Oe(n)&&!n.endList&&m&&!si(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var p,y=di(null==(p=t.response)?void 0:p.code),E=li(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===vi||(o.resolved=!0)}else this.state=l===fi?Sn:Tn;this.tickImmediate()}else this.state=Tn}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!di(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=hn)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===pn||this.state===yn){var t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.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(i," 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,i){if(e){var r=ji.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),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,i,r){var n=this,a=i.details;if(a){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=r?0:jr(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n);return n.hls.trigger(ee.LEVEL_PTS_UPDATED,{details:a,level:i,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1)){var s,o=null===(null==(s=this.transmuxer)?void 0:s.error);if((0===i.fragmentError||o&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),o){var l=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(l.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(i.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,i,r=!(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=r&&!n?e.startPTS:(n||e).start)?t:NaN).toFixed(3),"-").concat((null!=(i=r&&!n?e.endPTS:(n||e).end)?i: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)))}}])}(Vi);function bn(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,i=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var i=new Uint8Array(t),r=0,n=0;n<e.length;n++){var a=e[n];i.set(a,r),r+=a.length}return i}(t,i),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,i="~";function r(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,r,a,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new n(r,a||e,s),l=i?i+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 r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,n=[];if(0===this._eventsCount)return n;for(r in e=this._events)t.call(e,r)&&n.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,a=r.length,s=new Array(a);n<a;n++)s[n]=r[n].fn;return s},o.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,n,a,s){var o=i?i+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,r),!0;case 4:return c.fn.call(c.context,t,r,n),!0;case 5:return c.fn.call(c.context,t,r,n,a),!0;case 6:return c.fn.call(c.context,t,r,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,r);break;case 4:c[u].fn.call(c[u].context,t,r,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,i){return a(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,r,n){var a=i?i+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||r&&o.context!==r||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||n&&!o[l].once||r&&o[l].context!==r)&&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=i?i+e:e,this._events[t]&&s(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(Rn)),Rn.exports),Pn=Ie(wn),Dn="1.6.15",Cn={};function _n(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 xn(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 i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3]}function On(e,t){for(var i=t,r=0;xn(e,t);){r+=10,r+=Mn(e,t+6),_n(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)}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 Bn(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Un(e,t){return t+1<e.length&&Fn(e,t)}function Gn(e,t){if(Un(e,t)){var i=Nn(e,t);if(t+i>=e.length)return!1;var r=Bn(e,t);if(r<=i)return!1;var n=t+r;return n===e.length||Un(e,n)}return!1}function Vn(e,t,i,r,n){if(!e.samplerate){var a=function(e,t,i,r){var n=t[i+2],a=n>>2&15;if(!(a>12)){var s=1+(n>>6&3),o=t[i+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 Te.log("manifest codec:".concat(r,", 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:r}}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,i,r,n);if(!a)return;de(e,a)}}function Hn(e){return 9216e4/e}function Kn(e,t,i,r,n){var a,s=r+n*Hn(e.samplerate),o=function(e,t){var i=Nn(e,t);if(t+i<=e.length){var r=Bn(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,i+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(i+u,t.length),0):a=t.subarray(i+u,i+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-i;return(a=new Uint8Array(f)).set(t.subarray(i,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}function jn(e,t){return xn(e,t)&&Mn(e,t+6)+10<=e.length-t}function Wn(e){return function(e,t,i,r){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),a=1;"BYTES_PER_ELEMENT"in r&&(a=r.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(i,0),o));var d;return new r(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 qn(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var i=e.data.subarray(1).indexOf(0);if(-1!==i){var r=Ae(Wn(e.data,1,i)),n=e.data[2+i],a=e.data.subarray(3+i).indexOf(0);if(-1!==a){var s,o=Ae(Wn(e.data,3+i,a));return s="--\x3e"===r?Ae(Wn(e.data,4+i+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+i+a)),t.mimeType=r,t.pictureType=n,t.description=o,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function Yn(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Ae(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,i=Ae(e.data.subarray(t),!0);t+=i.length+1;var r=Ae(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Ae(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?qn(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,i=Ae(e.data.subarray(t),!0);t+=i.length+1;var r=Ae(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Ae(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]),i=Mn(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}function Xn(e){for(var t=0,i=[];xn(e,t);){var r=Mn(e,t+6);e[t+5]>>6&1&&(t+=10);for(var n=(t+=10)+r;t+10<n;){var a=zn(e.subarray(t)),s=Yn(a);s&&i.push(s),t+=a.size+10}_n(e,t)&&(t+=10)}return i}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),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Jn(e){for(var t=Xn(e),i=0;i<t.length;i++){var r=t[i];if(Qn(r))return $n(r)}}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,i,r){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,i){}},{key:"demux",value:function(e,t){this.cachedData&&(e=rt(this.cachedData,e),this.cachedData=null);var i,r=On(e,0),n=r?r.length:0,a=this._audioTrack,s=this._id3Track,o=r?Jn(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&X(o))&&(this.basePTS=ia(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,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,i=n+=u.length):n=l}else jn(e,n)?(r=On(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY}),i=n+=r.length):n++;if(n===l&&i!==l){var c=e.slice(i);this.cachedData?this.cachedData=rt(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:ea(),id3Track:s,textTrack:ea()}}},{key:"demuxSampleAes",value:function(e,t,i){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}}])}(),ia=function(e,t,i){return X(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0)},ra=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,i,r,n){if(!(i+24>t.length)){var a=ua(t,i);if(a&&i+a.frameLength<=t.length){var s=r+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(i,i+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 i=e[t+1]>>3&3,r=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*na[14*(3===i?3-r:3===r?3:4)+n-1],u=aa[3*(3===i?0:2===i?1:2)+a],c=3===o?1:2,d=sa[i][r],h=oa[r],f=8*d*h,v=Math.floor(d*l/u+s)*h;if(null===ra){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ra=g?parseInt(g[1]):0}return!!ra&&ra<=87&&2===r&&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 i=ua(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);var n=t+r;return n===e.length||da(e,n)}return!1}var fa=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t)).observer=void 0,r.config=void 0,r.observer=e,r.config=i,r}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,i,r,n){E(t,"resetInitSegment",this,3)([e,i,r,n]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,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)&&Bn(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,i){Vn(e,this.observer,t,i,e.manifestCodec);var r=Kn(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}}],[{key:"probe",value:function(e,t){if(!e)return!1;var i=On(e,0),r=(null==i?void 0:i.length)||0;if(ha(e,r))return!1;for(var n=e.length;r<n;r++)if(Gn(e,r))return t.log("ADTS sync word found !"),!0;return!1}}])}(ta),va=function(e,t){var i=0,r=5;t+=r;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);r>0;){s[0]=e[t];var o=Math.min(r,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,i=i?i<<o|n[0]:n[0],t+=1,r-=o}return i},ga=function(e){function t(e){var i;return a(this,t),(i=n(this,t)).observer=void 0,i.observer=e,i}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,i,r,n){E(t,"resetInitSegment",this,3)([e,i,r,n]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,i){var r=ma(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0);if(!t)return!1;var i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Jn(t)&&va(e,i)<16}}])}(ta);function ma(e,t,i,r,n){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;var a=t[i+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[i+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(i+l>t.length)return-1;var u=t[i+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[i+6]<<8|t[i+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[i+5]>>3,v=7&t[i+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),m=r+n*(1536/s*9e4),p=t.subarray(i,i+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:p,pts:m}),l}var pa=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,i,r,n){E(t,"resetInitSegment",this,3)([e,i,r,n]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,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,i){if(null!==this.basePTS)return la(e,t,i,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Jn(t)&&va(e,i)<=16)return!1;for(var r=e.length;i<r;i++)if(ha(e,i))return Te.log("MPEG Audio sync word found !"),!0;return!1}}])}(ta),ya=/\/emsg[-/]ID3/i,Ea=function(){return o(function e(t,i){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=i},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,i,r){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,m=f.codec;a.id=v,a.timescale=g,a.codec=m}s.id=Ve.text,n.sampleDuration=0,n.duration=a.duration=r}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t){this.timeOffset=t;var i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=rt(this.remainderData,e));var a=function(e){var t={valid:null,remainder:null},i=Ye(e,["moof"]);if(i.length<2)return t.remainder=e,t;var r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=a.remainder,r.samples=a.valid||new Uint8Array}else r.samples=i;var s=this.extractID3Track(r,t);return n.samples=nt(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}},{key:"flush",value:function(){var e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(t,this.timeOffset);return i.samples=nt(e,t),{videoTrack:t,audioTrack:ea(),id3Track:r,textTrack:ea()}}},{key:"extractID3Track",value:function(e,t){var i=this,r=this.id3Track;if(e.samples.length){var n=Ye(e.samples,["emsg"]);n&&n.forEach(function(e){var n=function(e){var t=e[0],i="",r="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==He(e.subarray(u,u+1));)i+=He(e.subarray(u,u+1)),u+=1;for(i+=He(e.subarray(u,u+1)),u+=1;"\0"!==He(e.subarray(u,u+1));)r+=He(e.subarray(u,u+1)),u+=1;r+=He(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,Te.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"!==He(e.subarray(u,u+1));)i+=He(e.subarray(u,u+1)),u+=1;for(i+=He(e.subarray(u,u+1)),u+=1;"\0"!==He(e.subarray(u,u+1));)r+=He(e.subarray(u,u+1)),u+=1;r+=He(e.subarray(u,u+1)),u+=1}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(ya.test(n.schemeIdUri)){var a=Ta(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;r.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Zn.emsg,duration:s})}else if(i.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=Ta(n,t);r.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Zn.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}},{key:"demuxSampleAes",value:function(e,t,i){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,i=0;i<t;){var r=je(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)}}])}();function Ta(e,t){return X(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var ka=function(){return o(function e(t,i,r){a(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Oi(i,{removePKCS7Padding:!1})},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Di)}},{key:"decryptAacSample",value:function(e,t,i){var r=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),r.decrypter.isSync()||r.decryptAacSamples(e,t+1,i)}).catch(i)}}},{key:"decryptAacSamples",value:function(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var i=new Uint8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}},{key:"decryptAvcSample",value:function(e,t,i,r,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,i+1,r)}).catch(r)}},{key:"decryptAvcSamples",value:function(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();for(var n=e[t].units;!(i>=n.length);i++){var a=n[i];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,i,r,a),this.decrypter.isSync())))return}}}}])}(),Sa=function(){return o(function e(){a(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){var n=r.units;i=n[n.length-1]}return i}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var i=t.samples,r=i.length;if(!r)return void t.dropped++;var n=i[r-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,i){var r,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(r=t[u++],s)if(1!==s)if(r)if(1===r){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=rt(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=r?0:2;else s=r?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=rt(g.data,t))}return e.naluState=s,l}}])}(),Aa=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,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.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),i=this.word>>>32-t;if(e>32&&Te.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?i<<t|this.readBits(t):i}},{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)}}])}(),ba=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,i,r){var n,a=this,s=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(function(r){var s,u;switch(r.type){case 1:var c=!1;n=!0;var d,h=r.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,i.pts,i.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,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,ot(r.data,1,i.pts,t.samples);break;case 7:var v,g;n=!0,l=!0;var m=r.data,p=a.readSPS(m);if(!e.sps||e.width!==p.width||e.height!==p.height||(null==(v=e.pixelRatio)?void 0:v[0])!==p.pixelRatio[0]||(null==(g=e.pixelRatio)?void 0:g[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[m];for(var y=m.subarray(1,4),E="avc1.",T=0;T<3;T++){var k=y[T].toString(16);k.length<2&&(k="0"+k),E+=k}e.codec=E}break;case 8:n=!0,e.pps=[r.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,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(r)}),r&&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 Aa(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var i=8,r=8,n=0;n<e;n++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r}},{key:"readSPS",value:function(e){var t,i,r,n=new Aa(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),m=this.skipScalingList.bind(this);u();var p=u();if(c(5),f(3),u(),g(),100===p||110===p||122===p||244===p||44===p||83===p||86===p||118===p||128===p){var y=d();if(3===y&&f(1),g(),g(),f(1),h())for(i=3!==y?8:12,r=0;r<i;r++)h()&&m(r<6?16:64,n)}g();var E=d();if(0===E)d();else if(1===E)for(f(1),v(),v(),t=d(),r=0;r<t;r++)v();g(),f(1);var T=d(),k=d(),S=c(1);0===S&&f(1),f(1),h()&&(a=d(),s=d(),o=d(),l=d());var A=[1,1];if(h()&&h())switch(u()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(T+1)-2*a-2*s),height:(2-S)*(k+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}])}(Sa),La=function(e){function t(){var e;a(this,t);for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return(e=n(this,t,[].concat(r))).initVPS=null,e}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,i,r){var n,a=this,s=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(function(r){var s,u;switch(r.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,i.pts,i.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,i.pts,i.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,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 39:n=!0,ot(r.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!==S(e.params)&&(e.params={}),e.params=de(e.params,a.readVPS(r.data)),a.initVPS=r.data),e.vps=[r.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],r.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var d=a.readSPS(r.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,r.data,e.vps),o||(o=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),o.key=!0;break;case 34:if(n=!0,"object"===S(e.params)){if(!e.pps){e.pps=[];var f=a.readPPS(r.data);for(var v in f)e.params[v]=f[v]}a.pushParameterSet(e.pps,r.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,i.pts,i.dts));break;default:n=!1}o&&n&&o.units.push(r)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,i){(i&&i[0]===this.initVPS||!i&&!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),i=0,r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}},{key:"pushAccessUnit",value:function(e,i){E(t,"pushAccessUnit",this,3)([e,i]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new Aa(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 Aa(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var i=t.readBits(3);t.readBoolean();for(var r=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(),m=t.readUByte(),p=[],y=[],E=0;E<i;E++)p.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(var T=i;T<8;T++)t.readBits(2);for(var k=0;k<i;k++)p[k]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[k]&&t.readUByte();t.readUEG();var S=t.readUEG();3==S&&t.skipBits(1);var A=t.readUEG(),b=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 D=t.readUEG(),C=t.readUEG(),_=t.readUEG(),x=t.readBoolean()?0:i;x<=i;x++)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 B=t.readUEG(),U=0,G=0;G<B;G++){var V=!1;if(0!==G&&(V=t.readBoolean()),V){G===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var H=0,K=0;K<=U;K++){var j=t.readBoolean(),W=!1;j||(W=t.readBoolean()),(j||W)&&H++}U=H}else{var q=t.readUEG(),Y=t.readUEG();U=q+Y;for(var z=0;z<q;z++)t.readUEG(),t.readBoolean();for(var X=0;X<Y;X++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var Q=t.readUEG(),$=0;$<Q;$++){for(var J=0;J<_+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,ie=!0,re=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(re=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<=i;ue++){var ce=!1;(ie=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=A,ge=b;if(L){var me=1,pe=1;1===S?me=pe=2:2==S&&(me=2),ve=A-me*R-me*I,ge=b-pe*P-pe*w}for(var ye=r?["A","B","C"][r]:"",Ee=s<<24|o<<16|l<<8|u,Te=0,ke=0;ke<32;ke++)Te=(Te|(Ee>>ke&1)<<31-ke)>>>0;var Se=Te.toString(16);1===a&&"2"===Se&&(Se="6");var Ae=n?"H":"L";return{codecString:"hvc1.".concat(ye).concat(a,".").concat(Se,".").concat(Ae).concat(m,".B0"),params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:m,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:C,min_spatial_segmentation_idc:Z,chroma_format_idc:S,frame_rate:{fixed:ie,fps:ne/re}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new Aa(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 i=t.readBoolean(),r=t.readBoolean(),n=1;return r&&i?n=0:r?n=3:i&&(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,i,r,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=i,this.typeSupported=r,this.logger=n,this.videoParser=null}return o(e,[{key:"resetInitSegment",value:function(t,i,r,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=i,this.videoCodec=r}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,i=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,i){var r,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,m=null,p=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=rt(this.remainderData,t)).length,this.remainderData=null),E<Ia&&!a)return this.remainderData=t,{audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};var T=Math.max(0,e.syncOffset(t));(E-=(E-T)%Ia)<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var k=0,S=T;S<E;S+=Ia)if(71===t[S]){var A=!!(64&t[S+1]),b=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(b){case c:A&&(d&&(r=xa(d,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,u,r,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(L,S+Ia)),d.size+=S+Ia-L);break;case h:if(A){if(v&&(r=xa(v,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r)}v={data:[],size:0}}v&&(v.data.push(t.subarray(L,S+Ia)),v.size+=S+Ia-L);break;case f:A&&(g&&(r=xa(g,this.logger))&&this.parseID3PES(l,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(L,S+Ia)),g.size+=S+Ia-L);break;case 0:A&&(L+=t[L]+1),y=this._pmtId=Pa(t,L);break;case y:A&&(L+=t[L]+1);var I=Da(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===m||p||(this.logger.warn("MPEG-TS PMT found at ".concat(S," after unknown PID '").concat(m,"'. Backtracking to sync byte @").concat(T," to parse all TS packets.")),m=null,S=T-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=b}}else k++;k>0&&Ca(this.observer,new Error("Found ".concat(k," 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,i=e.audioTrack,r=e.videoTrack,n=e.id3Track,a=e.textTrack,s=r.pesData,o=i.pesData,l=n.pesData;if(s&&(t=xa(s,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,a,t,!0),r.pesData=null)):r.pesData=s,o&&(t=xa(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=xa(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l}},{key:"demuxSampleAes",value:function(e,t,i){var r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new ka(this.observer,this.config,t);return this.decrypt(r,n)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new ba:"hevc"===e&&(this.videoParser=new La))}},{key:"decrypt",value:function(e,t){return new Promise(function(i){var r=e.audioTrack,n=e.videoTrack;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,function(){n.samples?t.decryptAvcSamples(n.samples,0,0,function(){i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,function(){i(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 i,r,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=rt(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(i=a,r=o.length;i<r-1&&!Un(o,i);i++);if(i!==a){var d,h=i<r-1;if(d=h?"AAC PES did not start with ADTS header,offset:".concat(i):"No ADTS header found in AAC PES",Ca(this.observer,new Error(d),h,this.logger),!h)return}if(Vn(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)n=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=Hn(e.samplerate);n=s.sample.pts+f}for(var v,g=0;i<r;){if(i+=(v=Kn(e,o,i,n,g)).length,v.missing){this.aacOverFlow=v;break}for(g++;i<r-1&&!Un(o,i);i++);}}},{key:"parseMPEGPES",value:function(e,t){var i=t.data,r=i.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<r;)if(da(i,a)){var o=la(e,i,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 i=t.data,r=t.pts;if(void 0!==r)for(var n,a=i.length,s=0,o=0;o<a&&(n=ma(e,i,o,r,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 i=de({},t,{type:this._videoTrack?Zn.emsg:Zn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}}],[{key:"probe",value:function(t,i){var r=e.syncOffset(t);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset ".concat(r)),-1!==r}},{key:"syncOffset",value:function(e){for(var t=e.length,i=Math.min(940,t-Ia)+1,r=0;r<i;){for(var n=!1,a=-1,s=0,o=r;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)&&(i=Math.min(a+18612,e.length-Ia)+1),n||(n=0===wa(e,o)),n&&s>1&&(0===a&&s>2||o+Ia>i))return a}r++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Ve[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 Da(e,t,i,r,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(!r){_a("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(!r){_a("H.264",a);break}case 27:-1===s.videoPid&&(s.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){_a("AC-3",a);break}case 129:i.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!==i.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 Ca(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 Ca(e,t,i,r){r.warn("parsing error: ".concat(t.message)),e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function _a(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function xa(e,t){var i,r,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]=rt(l[0],l[1]),l.splice(1,1);if(1===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;var u=i[7];192&u&&(a=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&u?a-(s=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[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=i[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=(i=l[h]).byteLength;if(c){if(c>v){c-=v;continue}i=i.subarray(c),v-=c,c=0}d.set(i,o),o+=v}return r&&(r-=n+3),{data:d,pts:a,dts:s,len:r}}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 i=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]),r=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:i,audio:r};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,i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];for(var a=r.length,s=a;a--;)t+=r[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(r[a],t),t+=r[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,i){i*=t;var r=Math.floor(i/(Oa+1)),n=Math.floor(i%(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,r>>24,r>>16&255,r>>8&255,255&r,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,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))}},{key:"moov",value:function(t){for(var i=t.length,r=[];i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var i=t.length,r=[];i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex].concat(r))}},{key:"mvhd",value:function(t,i){i*=t;var r=Math.floor(i/(Oa+1)),n=Math.floor(i%(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,r>>24,r>>16&255,r>>8&255,255&r,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 i,r,n=t.samples||[],a=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,a[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.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 i,r,n,a=[],s=[];for(i=0;i<t.sps.length;i++)n=(r=t.sps[i]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)n=(r=t.pps[i]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));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(T(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 i=t.segmentCodec;if("audio"===t.type){if("aac"===i)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===i&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===i&&"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"===i)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===i&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(i,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var i=t.id,r=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(r/(Oa+1)),o=Math.floor(r%(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,i>>24&255,i>>16&255,i>>8&255,255&i,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,i){var r=e.sdtp(t),n=t.id,a=Math.floor(i/(Oa+1)),s=Math.floor(i%(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,r.length+16+20+8+16+8+8),r)}},{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 i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,i){var r,n,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(i+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<c;r++)a=(n=u[r]).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*r);return e.box(e.types.trun,h)}},{key:"initSegment",value:function(t){e.types||e.init();var i=e.moov(t);return rt(e.FTYP,i)}},{key:"hvc1",value:function(t){for(var i=t.params,r=[t.vps,t.sps,t.pps],n=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),a=n.length,s=0;s<r.length;s+=1){a+=3;for(var o=0;o<r[s].length;o+=1)a+=2+r[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=r.length-1,c=0;c<r.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,r[c].length]),a),a+=3;for(var d=0;d<r[c].length;d+=1)l.set(new Uint8Array([r[c][d].length>>8,255&r[c][d].length]),a),a+=2,l.set(r[c][d],a),a+=r[c][d].length}var h=e.box(e.types.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],m=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,m>>24,m>>16&255,m>>8&255,255&m])))}}])}();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 i=e*t*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(i):i}function Ba(e){return Na(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function Ua(e){var t=e.baseTime,i=e.timescale,r=e.trackId;return"".concat(t/i," (").concat(t,"/").concat(i,") trackId: ").concat(r)}var Ga=null,Va=null;function Ha(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ka=function(e){function t(e,i,r,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=i,o.typeSupported=r,o.ISGenerated=!1,null===Ga){var l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ga=l?parseInt(l[1]):0}if(null===Va){var u=navigator.userAgent.match(/Safari\/(\d+)/i);Va=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?Ua(t):t," > ").concat(e?Ua(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,i=e[0].pts,r=e.reduce(function(e,r){var n=r.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=ja(n,i))-e),a>0?e:n},i);return t&&this.debug("PTS rollover detected"),r}},{key:"remux",value:function(e,t,i,r,n,a,s,o){var l,u,c,d,h,f,v=n,g=n,m=e.pid>-1,p=t.pid>-1,y=t.samples.length,E=e.samples.length>0,T=s&&y>0||y>1;if((!m||E)&&(!p||T)||this.ISGenerated||s){if(this.ISGenerated){var k,S,A,b,L=this.videoTrackConfig;(L&&(t.width!==L.width||t.height!==L.height||(null==(k=t.pixelRatio)?void 0:k[0])!==(null==(S=L.pixelRatio)?void 0:S[0])||(null==(A=t.pixelRatio)?void 0:A[1])!==(null==(b=L.pixelRatio)?void 0:b[1]))||!L&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));var I,R=this.isVideoContiguous,w=-1;if(T&&(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&&T){var D=this.getVideoStartPts(t.samples),C=(ja(e.samples[0].pts,D)-D)/t.inputTimeScale;v+=Math.max(0,C),g+=Math.max(0,-C)}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,p||T||o===se?g:void 0),T){var _=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,_)}}else T&&(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&&(i.samples.length&&(h=Wa(i,n,this._initPTS,this._initDTS)),r.samples.length&&(d=qa(r,n,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}},{key:"computeInitPts",value:function(e,t,i,r){var n=Math.round(i*t),a=ja(e,n);if(a<n+t)for(this.log("Adjusting PTS for rollover in timeline near ".concat((n-a)/t," ").concat(r));a<n+t;)a+=8589934592;return a-n}},{key:"generateIS",value:function(e,t,i,r){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||r,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,i,"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),m=ja(l[0].dts,g),p=this.computeInitPts(m,s,i,"video"),y=this.computeInitPts(g,s,i,"video");a=Math.min(a,p),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(r?"":"~").concat(i," ").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(i," 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,i,r){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,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||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?i=!0:h=y-E-d}for(var T=h+d,k=0;k<u;k++){var S=o[k];S.pts=ja(S.pts,T),S.dts=ja(S.dts,T),S.dts<o[k>0?k-1:k].dts&&(p=!0)}p&&o.sort(function(e,t){var i=e.dts-t.dts,r=e.pts-t.pts;return i||r}),n=o[0].dts;var A=(a=o[o.length-1].dts)-n,b=A?Math.round(A/(u-1)):v||e.inputTimeScale/30;if(i){var L=n-T,I=L>b,R=L<-1;if((I||R)&&(I?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ba(L,!0)," ms (").concat(L,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ba(-L,!0)," ms (").concat(L,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!R||T>=o[0].pts||Ga)){n=T;var w=o[0].pts-L;if(I)o[0].dts=n,o[0].pts=w;else for(var P=!0,D=0;D<o.length&&!(o[D].dts>w&&P);D++){var C=o[D].pts;if(o[D].dts-=L,o[D].pts-=L,D<o.length-1){var _=o[D+1].pts;P=_<=o[D].pts==_<=C}}this.log("Video: Initial PTS/DTS adjusted: ".concat(Ba(w,!0),"/").concat(Ba(n,!0),", delta: ").concat(Ba(L,!0)," ms"))}}for(var x=0,M=0,O=n=Math.max(0,n),F=0;F<u;F++){for(var N=o[F],B=N.units,U=B.length,G=0,V=0;V<U;V++)G+=B[V].data.length;M+=G,x+=U,N.length=G,N.dts<O?(N.dts=O,O+=b/4|0||1):O=N.dts,g=Math.min(N.pts,g),m=Math.max(N.pts,m)}a=o[u-1].dts;var H,K=M+4*x+8;try{H=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(H.buffer);j.setUint32(0,K),H.set(Fa.types.mdat,4);for(var W=!1,q=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<u;Q++){for(var $=o[Q],te=$.units,ie=0,re=0,ne=te.length;re<ne;re++){var ae=te[re],se=ae.data,oe=ae.data.byteLength;j.setUint32(f,oe),f+=4,H.set(se,f),f+=oe,ie+=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:b;if(le=Q>0?$.pts-o[Q-1].pts:b,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var he=Math.floor(ue.maxBufferHole*s),fe=(r?g+r*s:this.nextAudioTs+d)-$.pts;fe>he?((v=fe-ce)<0?v=ce:W=!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);q=Math.min(q,v),z=Math.max(z,v),Y=Math.min(Y,le),X=Math.max(X,le),l.push(Ha($.key,v,ie,ve))}if(l.length)if(Ga){if(Ga<70){var ge=l[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(Va&&X-Y<z-q&&b/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 me=n,pe=0,ye=l.length;pe<ye;pe++){var Ee=me+l[pe].duration,Te=me+l[pe].cts;if(pe<ye-1){var ke=Ee+l[pe+1].cts;l[pe].duration=ke-Te}else l[pe].duration=pe?l[pe-1].duration:b;l[pe].cts=0,me=Ee}}var Se=a+(v=W||!v?b:v);this.nextVideoTs=h=Se-d,this.videoSampleDuration=v,this.isVideoContiguous=!0;var Ae={data1:Fa.moof(e.sequenceNumber++,n,de(e,{samples:l})),data2:H,startPTS:(g-d)/s,endPTS:(m+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,Ae}},{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,i,r,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,m=u.baseTime*a/u.timescale,p=m+t*a;if(this.isAudioContiguous=i=i||f.length&&g>0&&(r&&Math.abs(p-(g+m))<9e3||Math.abs(ja(f[0].pts,p)-(g+m))<20*l),f.forEach(function(e){e.pts=ja(e.pts,p)}),!i||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(m," / ").concat(a,")")),!f.length)return;g=0===n?0:r&&!h?Math.max(0,p-m):f[0].pts-m}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,T=0,k=g+m;T<f.length;T++){var S=f[T],A=S.pts,b=A-k,L=Math.abs(1e3*b/a);if(b<=-E*l&&h)0===T&&(this.warn("Audio frame @ ".concat((A/a).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*b/a)," ms.")),this.nextAudioTs=g=A-m,k=A);else if(b>=E*l&&L<1e4&&h){var I=Math.round(b/l);for(k=A-I*l;k<0&&I&&l;)I--,k+=l;0===T&&(this.nextAudioTs=g=k-m),this.warn("Injecting ".concat(I," audio frames @ ").concat(((k-m)/a).toFixed(3),"s due to ").concat(Math.round(1e3*b/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(T,0,{unit:w,pts:k}),k+=l,T++}}S.pts=k,k+=l}for(var P,D=null,C=null,_=0,x=f.length;x--;)_+=f[x].unit.byteLength;for(var M=0,O=f.length;M<O;M++){var F=f[M],N=F.unit,B=F.pts;if(null!==C){d[M-1].duration=Math.round((B-C)/s)}else{if(i&&"aac"===e.segmentCodec&&(B=g+m),D=B,!(_>0))return;_+=v;try{P=new Uint8Array(_)}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:_,reason:"fail allocating audio mdat ".concat(_)})}c||(new DataView(P.buffer).setUint32(0,_),P.set(Fa.types.mdat,4))}P.set(N,v);var U=N.byteLength;v+=U,d.push(Ha(!0,o,U,0)),C=B}var G=d.length;if(G){var V=d[d.length-1];g=C-m,this.nextAudioTs=g+s*V.duration;var H=c?new Uint8Array(0):Fa.moof(e.sequenceNumber++,D/s,de({},e,{samples:d}));e.samples=[];var K=(D-m)/a,j=this.nextAudioTs/a,W={data1:H,data2:P,startPTS:K,endPTS:j,startDTS:K,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:G};return this.isAudioContiguous=!0,W}}}])}(ve);function ja(e,t){var i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function Wa(e,t,i,r){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-i.baseTime*a/i.timescale,t*a)/a,o.dts=ja(o.dts-r.baseTime*a/r.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function qa(e,t,i){var r=e.samples.length;if(r){for(var n=e.inputTimeScale,a=0;a<r;a++){var s=e.samples[a];s.pts=ja(s.pts-i.baseTime*n/i.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 Ya,za=function(e){function t(e,i,r,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,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t){var i=this.audioCodec,r=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 i=t.keyId;i&&t.isCommonEncryption&&tt(e,function(e,t){var r=e.subarray(8,24);r.some(function(e){return 0!==e})||(Te.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(be(r)," -> ").concat(be(i))),e.set(i,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&&(i=Qa(a,Ce,this)),s&&(r=Qa(s,_e,this));var l={};a&&s?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:i,encrypted:a.encrypted,initSegment:e,id:"audio"}:s?l.video={container:"video/mp4",codec:r,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,i,r,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,c={audio:void 0,video:void 0,text:r,id3:i,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,i){for(var r={},n=Ye(e,["moof","traf"]),a=0;a<n.length;a++){var s=n[a],o=Ye(s,["tfhd"])[0],l=je(o,4),u=t[l];if(u){r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:u.timescale,type:u.type});var c=r[l],d=Ye(s,["tfdt"])[0];if(d){var h=d[0],f=je(d,4);1===h&&(f===Ue?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=Ue+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),m=(null==v?void 0:v.duration)||0;8&g&&(m=je(o,2&g?12:8));for(var p=Ye(s,["trun"]),y=c.start||0,E=0,T=m,k=0;k<p.length;k++){var S=p[k],A=je(S,4),b=c.sampleCount;c.sampleCount+=A;var L=1&S[3],I=4&S[3],R=1&S[2],w=2&S[2],P=4&S[2],D=8&S[2],C=8,_=A;for(L&&(C+=4),I&&A&&(1&S[C+1]||void 0!==c.keyFrameIndex||(c.keyFrameIndex=b),C+=4,R?(T=je(S,C),C+=4):T=m,w&&(C+=4),D&&(C+=4),y+=T,E+=T,_--);_--;)R?(T=je(S,C),C+=4):T=m,w&&(C+=4),P&&(1&S[C+1]||void 0===c.keyFrameIndex&&(c.keyFrameIndex=c.sampleCount-(_+1),c.keyFrameStart=y),C+=4),D&&(C+=4),y+=T,E+=T;!E&&m&&(E+=m*A)}c.duration+=E}}if(!Object.keys(r).some(function(e){return r[e].duration})){for(var x=1/0,M=0,O=Ye(e,["sidx"]),F=0;F<O.length;F++){var N=ze(O[F]);if(null!=N&&N.references){x=Math.min(x,N.earliestPresentationTime/N.timescale);var B=N.references.reduce(function(e,t){return e+t.info.duration||0},0);M=Math.max(M,B+N.earliestPresentationTime/N.timescale)}}M&&X(M)&&Object.keys(r).forEach(function(e){r[e].duration||(r[e].duration=M*r[e].timescale-r[e].start)})}return r}(d,f,this),g=f.audio?v[f.audio.id]:null,m=f.video?v[f.video.id]:null,p=Xa(m,1/0),y=Xa(g,1/0),E=Xa(m,0,!0),T=Xa(g,0,!0),k=n,S=0,A=g&&(!m||!l&&y<p||l&&l.trackId===f.audio.id),b=A?g:m;if(b){var L=b.timescale,I=b.start-n*L,R=A?f.audio.id:f.video.id;k=b.start/L,S=A?T-y:E-p,!a&&l||!function(e,t,i,r){if(null===e)return!0;var n=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-i)>n}(l,k,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(k-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=k,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});var w=k-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 D=!!f.audio,C=!!f.video,_="";D&&(_+="audio"),C&&(_+="video");var x={data1:d,startPTS:w,startDTS:w,endPTS:P,endDTS:P,type:_,hasAudio:D,hasVideo:C,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=D&&!C?x:void 0,c.video=C?x:void 0;var M=null==m?void 0:m.sampleCount;if(M){var O=m.keyFrameIndex,F=-1!==O;x.nb=M,x.dropped=0===O||this.isVideoContiguous?0:F?O:M,x.independent=F,x.firstKeyFrame=O,F&&m.keyFrameStart&&(x.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=F),this.isVideoContiguous||(this.isVideoContiguous=F),x.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(O,"/").concat(M," dropped: ").concat(x.dropped," start: ").concat(x.firstKeyFramePTS||"NA"))}return c.initSegment=h,c.id3=Wa(i,n,l,l),r.samples.length&&(c.text=qa(r,n,l)),c}}])}(ve);function Xa(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(i?e.duration:0))/e.timescale:t}function Qa(e,t,i){var r=e.codec;if(r&&r.length>4)return r;if(t===Ce){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r){return kt(r,!1)}return i.warn('Unhandled audio codec "'.concat(r,'" in mp4 MAP')),r||"mp4a"}return i.warn('Unhandled video codec "'.concat(r,'" in mp4 MAP')),r||"avc1"}try{Ya=self.performance.now.bind(self.performance)}catch(e){Ya=Date.now}var $a=[{demux:Ea,remux:za},{demux:Ra,remux:Ka},{demux:fa,remux:Ka},{demux:pa,remux:Ka}];$a.splice(2,0,{demux:ga,remux:Ka});var Ja=function(){return o(function e(t,i,r,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=i,this.config=r,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,i,r){var n=this,a=i.transmuxing;a.executeStart=Ya();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var u=r||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,k=function(e,t){var i=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(s,t);if(k&&ar(k.method)){var S=this.getDecrypter(),A=sr(k.method);if(!S.isSync())return this.asyncResult=!0,this.decryptionPromise=S.webCryptoDecrypt(s,k.key.buffer,k.iv.buffer,A).then(function(e){var t=n.push(e,null,i);return n.decryptionPromise=null,t}),this.decryptionPromise;var b=S.softwareDecrypt(s,k.key.buffer,k.iv.buffer,A);if(i.part>-1){var L=S.flush();b=L?L.buffer:L}if(!b)return a.executeEnd=Ya(),Za(i);s=new Uint8Array(b)}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=Ya(),Za(i)}(d||h||g||I)&&this.resetInitSegment(T,m,p,E,t),(d||g||I)&&this.resetInitialTimestamp(y),c||this.resetContiguity();var w=this.transmux(s,k,v,f,i);this.asyncResult=es(w);var P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,a.executeEnd=Ya(),w}},{key:"flush",value:function(e){var t=this,i=e.transmuxing;i.executeStart=Ya();var r=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(r){var l=r.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){i.executeEnd=Ya();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(i){return t.flushRemux(s,i,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,i){var r=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(i.sn).concat(i.part>-1?" part: "+i.part:""," of ").concat(this.id===ae?"level":"track"," ").concat(i.level));var c=this.remuxer.remux(r,n,a,s,u,l,!0,this.id);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Ya()}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,i=this.remuxer;t&&i&&(t.resetTimeStamp(e),i.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,i,r,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(e,t,i,r),s.resetInitSegment(e,t,i,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,i,r,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,n):this.transmuxUnencrypted(e,i,r,n)}},{key:"transmuxUnencrypted",value:function(e,t,i,r){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,i,!1,this.id),chunkMeta:r}}},{key:"transmuxSampleAes",value:function(e,t,i,r,n){var a=this;return this.demuxer.demuxSampleAes(e,t,i).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,a.id),chunkMeta:n}})}},{key:"configureTransmuxer",value:function(e){for(var t,i=this.config,r=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(r,i,n,this.logger)),l&&l instanceof d||(this.demuxer=new d(r,i,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 Oi(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,i,r,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=i,this.initSegmentData=r,this.duration=n,this.defaultInitPts=s||null}),is=o(function e(t,i,r,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=i,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}),rs=0,ns=function(){return o(function e(t,i,r,n){var s=this;a(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=rs++,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,i=s.hls;if(i&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var r,n=null==(r=s.workerContext)?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.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,i.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=i,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=r,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(i,'"')),this.workerContext=function(e){var t=Cn[e];if(t)return t.clientCount++,t;var i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Cn[e]=r,r}(o.workerPath)):(c.log('injecting Web Worker for "'.concat(i,'"')),this.workerContext=function(){var e=Cn[Dn];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"}),i=self.URL.createObjectURL(t),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return Cn[Dn]=r,r}());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:i,config:Kt(o)})}catch(e){c.warn('Error setting up "'.concat(i,'" Web Worker, fallback to inline'),e),this.terminateWorker(),this.error=null,this.transmuxer=new Ja(this.observer,u,o,"",i,t.logger)}return}}this.transmuxer=new Ja(this.observer,u,o,"",i,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=rs++;var t=this.hls.config,i=Lt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,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=Cn[e||Dn];if(t&&1===t.clientCount--){var i=t.worker,r=t.objectURL;delete Cn[e||Dn],r&&self.URL.revokeObjectURL(r),i.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,i,r,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,m=n.decryptdata,p=this.frag,y=!(p&&n.cc===p.cc),E=!(p&&l.level===p.level),T=p?l.sn-p.sn:-1,k=this.part?l.part-this.part.index:-1,S=0===T&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!E&&(1===T||0===T&&(1===k||S&&k<=0)),b=self.performance.now();(E||T||0===n.stats.parsing.start)&&(n.stats.parsing.start=b),!a||!k&&A||(a.stats.parsing.start=b);var L=!(p&&(null==(c=n.initSegment)?void 0:c.url)===(null==(d=p.initSegment)?void 0:d.url)),I=new is(y,A,o,E,g,L);if(!A||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(A,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(L));var R=new ts(i,r,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:m,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(v){var w=v.push(e,m,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 i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:e});else if(r){var n=r.flush(e);es(n)?n.then(function(i){t.handleFlushResult(i,e)}).catch(function(i){t.transmuxerError(i,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}},{key:"transmuxerError",value:function(e,t,i){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:i}))}},{key:"handleFlushResult",value:function(e,t){var i=this;e.forEach(function(e){i.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),as=function(e){function t(e,i,r){var s;return a(this,t),(s=n(this,t,[e,i,r,"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 i=t.frag,r=t.id,n=t.initPTS,a=t.timescale,s=t.trackId;if(r===ae){var o=i.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=i,this.state===kn){var u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==o)&&this.syncWithAnchor(i,null==u?void 0:u.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(i,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 i,r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(!t||(null==r?void 0:r.cc)!==t.cc){var n=(r||e).cc,a=ri(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 i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @".concat(i.toFixed(3))),e=i,this.state=hn):this.state=mn,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 mn:var e=this.levels,i=this.trackId,r=null==e?void 0:e[i],n=null==r?void 0:r.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=kn}break;case gn:this.checkRetryDate();break;case kn: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,i=this.levels,r=this.media,n=this.trackId,a=t.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=i&&i[n]){var s=i[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=mn,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Ce,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&&r){var m=v;o.PTSKnown&&m<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var p=this.getNextFragment(g,o);if(p&&this.isLoopLoading(p,g)&&(p=this.getNextFragmentLoopLoading(p,o,u,ae,d)),p){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Oe(p)&&!p.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Li&&(this.mainFragLoading=y=null),y&&Oe(y))){if(p.start>y.end){var E=this.fragmentTracker.getFragAtPos(g,ae);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,s,g)}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(e,i){this.bufferFlushed=this.flushing=!1,E(t,"onMediaDetaching",this,3)([e,i])}},{key:"onAudioTracksUpdated",value:function(e,t){var i=t.audioTracks;this.resetTransmuxer(),this.levels=i.map(function(e){return new Gt(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var i=!!t.url;this.trackId=t.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(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 i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ee.AUDIO_TRACK_LOADED,i))}},{key:"onAudioTrackLoaded",value:function(e,t){var i,r=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(r){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==dn&&(this.state=mn));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=r[a],c=0;if(n.live||null!=(i=u.details)&&i.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!==mn||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,i=e.frag,r=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(i.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[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==h){var v=r?r.index:-1,g=-1!==v,m=new Hi(i.level,i.sn,i.stats.chunkCount,n.byteLength,v,g);d.push(n,f,c,"",i,r,u.totalduration,!1,m,h)}else{this.log("Unknown video PTS for cc ".concat(i.cc,", waiting for video PTS before demuxing audio frag ").concat(i.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new Ln,complete:!1}).cache.push(new Uint8Array(n)),this.state!==dn&&(this.state=kn)}}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(i.sn," of level ").concat(i.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 i=t.tracks.audio;i&&(this.mediaBuffer=i.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 i=t.frag,r=t.part;if(i.type===se)if(this.fragContextChanged(i))this.warn("Fragment ".concat(i.sn).concat(r?" p: "+r.index:""," of level ").concat(i.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if(Oe(i)){this.fragPrevious=i;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},n)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==ae||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"onError",value:function(e,i){var r;if(i.fatal)this.state=Tn;else switch(i.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,i);break;case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==mn||(null==(r=i.context)?void 0:r.type)!==re||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)||this.resetLoadingState();break;case Z.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,E(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]));break;case Z.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==_e&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var i=t.type;if(i!==_e){this.flushing=!1,this.bufferFlushed=!0,this.state===En&&(this.state=hn);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,se),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var t,i="audio",r=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=pn,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),r.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:i,tracks:v.tracks})}if(d){var m=d.startPTS,p=d.endPTS,y=d.startDTS,E=d.endDTS;l&&(l.elementaryStreams[Ce]={startPTS:m,endPTS:p,startDTS:y,endDTS:E}),o.setElementaryStreamInfo(Ce,m,p,y,E),this.bufferFragmentData(d,o,l,a)}if(null!=f&&null!=(t=f.samples)&&t.length){var T=de({id:i,frag:o,details:c},f);r.trigger(ee.FRAG_PARSING_METADATA,T)}if(h){var k=de({id:i,frag:o,details:c},h);r.trigger(ee.FRAG_PARSING_USERDATA,k)}}else this.fragmentTracker.removeFragment(o)}else this.resetWhenMissingContext(a)}},{key:"_bufferInitSegment",value:function(e,t,i,r){if(this.state===pn&&(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:i,part:null,chunkMeta:r,parent:i.type,data:s};this.hls.trigger(ee.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,i,r){var n,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===Si||a===bi)if(Oe(e))if(null!=(n=i.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=kn;var s=this.mainDetails;s&&s.fragmentStart!==i.details.fragmentStart&&on(i.details,s)}else E(t,"loadFragment",this,3)([e,i,r]);else this._loadInitSegment(e,i);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;zt({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.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))}}])}(An),ss=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[i,e.logger])).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=e,r}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,i){var r=null==t?void 0:t.renditionReports;if(r){for(var n=-1,a=0;a<r.length;a++){var s=r[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=r[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=i&&Bt(i);return new Ut(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,i){var r=t.details,n=t.stats,a=self.performance.now(),s=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-s;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach(function(e){e.setStart(e.playlistOffset+l)})}if(r.live||null!=i&&i.live){var u="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){Wr(i,r,this);var c=r.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:r.url,error:c,reason:c.message,level:t.level||void 0,parent:null==(h=r.fragments[0])?void 0:h.type,networkDetails:f,stats:n})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=n.loading.start);var v,g=this.hls.mainForwardBufferInfo,m=g?g.end-g.len:0,p=Xr(r,1e3*(r.edge-m));if(r.requestScheduled+p<a?r.requestScheduled=a:r.requestScheduled+=p,this.log("live playlist ".concat(e," ").concat(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var T=this.hls.config.lowLatencyMode,k=r.lastPartSn,S=r.endSN,A=r.lastPartIndex,b=k===S;-1!==A?b?(y=S+1,E=T?0:A):(y=k,E=T?A+1:r.maxPartIndex):y=S+1;var L=r.age,I=L+r.ageHeader,R=Math.min(I-r.partTarget,1.5*r.targetduration);if(R>0){if(I>3*r.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!=i&&i.tuneInGoal&&I-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(i.tuneInGoal," to: ").concat(R," with playlist age: ").concat(r.age)),R=0;else{var w=Math.floor(R/r.targetduration);if(y+=w,void 0!==E)E+=Math.round(R%r.targetduration/r.partTarget);this.log("CDN Tune-in age: ".concat(r.ageHeader,"s last advanced ").concat(L.toFixed(2),"s goal: ").concat(R," skip sn ").concat(w," to part ").concat(E))}r.tuneInGoal=R}if(v=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E),T||!b)return r.requestScheduled=a,void this.loadingPlaylist(u,v)}else(r.canBlockReload||r.canSkipUntil)&&(v=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E));v&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(p-2*s,p/2)),this.scheduleLoading(u,v,r)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,i){var r=this,n=i||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 r.loadingPlaylist(e,t)},o)}}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,i,r){var n=Bt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=Ot),new Ut(i,r,n)}},{key:"checkRetry",value:function(e){var t=this,i=e.details,r=ni(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===gi||!n.resolved&&s===fi);if(c){var d;if(l>=u.maxNumRetry)return!1;if(r&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(i,'" without delivery-directives')),this.loadPlaylist();else{var h=li(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(i,'" 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 i=0;i<e.length;i++)if(!ls(e[i].attrs,t[i].attrs))return!1;return!0}function ls(e,t,i){var r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(i){return e[i]!==t[i]})}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 i;return a(this,t),(i=n(this,t,[e,"audio-track-controller"])).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,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_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 i=t.id,r=t.groupId,n=t.details,a=this.tracksInGroup[i];if(a&&a.groupId===r){var s=a.details;a.details=t.details,this.log("Audio track ".concat(i,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(r," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),i===this.trackId&&this.playlistLoaded(i,t,s)}else this.warn("Audio track with id:".concat(i," and group:").concat(r," 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 i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(function(e){return-1===(null==r?void 0:r.indexOf(e))})){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!i||-1!==i.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=Yt(s,a,Xt);if(o>-1)n=a[o];else{var l=Yt(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==i?void 0:i.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!==re||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 i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&zt(e,r,Xt))return r;var n=Yt(e,this.tracksInGroup,Xt);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n),a}if(r){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,i,r,n){var a=t[r],s=t.reduce(function(e,t,i){var r=t.uri;return(e[r]||(e[r]=[])).push(i),e},{})[a.uri];s.length>1&&(r=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),c=Qt(t,r,function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var r=t.audioGroups,a=i.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});return Yt(e,a,n)>-1});return c>-1?c:Qt(t,r,function(t){var r=t.audioGroups,a=i.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});return Yt(e,a,n)>-1})}(e,t.levels,i,s,Xt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=Yt(e,i);if(l>-1)return i[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 i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(!(e===this.trackId&&r===i&&n||(this.log("Switching to audio-track ".concat(e,' "').concat(r.name,'" lang:').concat(r.lang," group:").concat(r.groupId," channels:").concat(r.channels)),this.trackId=e,this.currentTrack=r,this.hls.trigger(ee.AUDIO_TRACK_SWITCHING,fe({},r)),n))){var a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,i=0;i<t.length;i++){var r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||zt(e,r,Xt)))return i}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 i=this.currentTrack;this.shouldLoadPlaylist(i)&&$t(i.url,this.hls)&&this.scheduleLoading(i,e)}},{key:"loadingPlaylist",value:function(e,i){E(t,"loadingPlaylist",this,3)([e,i]);var r=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,i),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(r,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.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:r,groupId:n,deliveryDirectives:i||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,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(r,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(i){if(t.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(r)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(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 i=t[0];try{i.execute()}catch(t){var r;if(i.onError(t),null===this.queues||null===this.tracks)return;var n=null==(r=this.tracks[e])?void 0:r.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,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?"SourceBuffer".concat(r.updating?" updating":"").concat(i.ended?" ended":"").concat(i.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 i;return a(this,t),(i=n(this,t,[e])).name=fs,i}return d(t,e),o(t)}(L(Error)),gs=function(e){function t(e,i){var r,s;return a(this,t),(r=n(this,t,["buffer-controller",e.logger])).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(e){var t;r.hls&&"open"===(null==(t=r.mediaSource)?void 0:t.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(e){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(e){var t=r,i=t.media,n=t.mediaSource;e&&r.log("Media source opened"),i&&n&&(n.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(ee.MEDIA_ATTACHED,{media:i,mediaSource:n}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var e=r,t=e.mediaSrc,i=e._objectUrl;t!==i&&r.error("Media element src was set while attaching MediaSource (".concat(i," > ").concat(t,")"))},r.hls=e,r.fragmentTracker=i,r.appendSource=(s=ke(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),r.initTracks(),r.registerListeners(),r}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,i=this.mediaSource;if(!t)return null;var r={};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===i?de(r,s.tracks):this.sourceBuffers.forEach(function(t){var i=p(t,1)[0];i&&(r[i]=de({},e.tracks[i]),e.removeBuffer(i)),t[0]=t[1]=null}),{media:t,mediaSource:i,tracks:r}}},{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 i,r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log("".concat(r," bufferCodec event(s) expected.")),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var i=this.media=t.media;this.transferData=this.overrides=void 0;var r=ke(this.appendSource);if(r){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&a instanceof o,ms(i),function(e,t){var i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,s),i.load()}catch(e){i.src=s}else i.src=s}i.addEventListener("emptied",this._onMediaEmptied)}}},{key:"assignMediaSource",value:function(e){var t,i;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(i=e.constructor)?void 0:i.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,i=this.transferData;if(i&&t){var r=this.tracks,n=i.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(r,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,r)){i.mediaSource=null,i.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(r),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(ee.MEDIA_DETACHING,{}),this.onMediaAttaching(ee.MEDIA_ATTACHING,i),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var i=t,r=n[i];if(r){var a=r.buffer;if(a){var s=e.fragmentTracker,o=r.id;if(s.hasFragments(o)||s.hasParts(o)){var l=ji.getBuffered(a);s.detectEvictedFragments(i,l,o,null,!0)}var u=ps(i),c=[i,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(i),e.trackSourceBuffer(i,r)}}}),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 i=this,r=!!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(r?"transferring":"detaching")),r)this.sourceBuffers.forEach(function(e){var t=p(e,1)[0];t&&i.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),r||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&ms(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 i=p(t,1)[0];i&&e.resetBuffer(i)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn("onBufferReset ".concat(e),t)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[ps(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 i,r=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 i,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==(i=r.transferData)||null==(i=i.tracks)?void 0:i[e],g=null!=v&&v.buffer?v:f,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=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(m,p),E=null==y?void 0:y.replace(hs,"$1"),T=St(l,u),k=null==(a=T)?void 0:a.replace(hs,"$1");T&&y&&E!==k&&("audio"===e.slice(0,5)&&(T=kt(T,r.appendSource)),r.log("switching codec ".concat(m," to ").concat(T)),T!==(f.pendingCodec||f.codec)&&(f.pendingCodec=T),f.container=c,r.appendChangeType(e,c,T))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(i=t.audio)?void 0:i.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,i){var r=e.tracks[i];return t[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,i){var r=this,n="".concat(t,";codecs=").concat(i),a={label:"change-type=".concat(n),execute:function(){var a=r.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(r.log("changing ".concat(e," sourceBuffer type to ").concat(n)),s.changeType(n),a.codec=i,a.container=t)}r.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.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,i=this,r=e.start,n=r+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(r,ae))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t=i.tracks.video;(i.lastVideoAppendEnd>n||null!=t&&t.buffer&&ji.isBuffered(t.buffer,n)||!0===(null==(e=i.fragmentTracker.getAppendedFrag(n,ae))?void 0:e.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){i.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 i=this,r=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,m=l?l.stats.buffering:null;0===g.start&&(g.start=v),m&&0===m.start&&(m.start=v);var y=r.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 T=r.video,k=null==T?void 0:T.buffer;if(k&&"initSegment"!==h){var S=l||o,A=this.blockedAudioAppend;if("audio"!==a||"main"===s||this.blockedAudioAppend||T.ending||T.ended){if("video"===a){var b=S.end;if(A){var L=A.frag.start;(b>L||b<this.lastVideoAppendEnd||ji.isBuffered(k,L))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}else{var I=S.start+.05*S.duration,R=k.buffered,w=this.currentOp("video");R.length||w?!w&&!ji.isBuffered(k,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(S):this.blockAudio(S)}}var P=(l||o).start,D={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=i.tracks[a])?void 0:e.buffer;t&&(E?i.updateTimestampOffset(t,P,.1,a,h,f):void 0!==c&&X(c)&&i.updateTimestampOffset(t,c,1e-6,a,h,f)),i.appendExecutor(n,a)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),m&&0===m.first&&(m.first=e);var t={};i.sourceBuffers.forEach(function(e){var i=p(e,2),r=i[0],n=i[1];r&&(t[r]=ji.getBuffered(n))}),i.appendErrors[a]=0,"audio"===a||"video"===a?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(ee.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:o.type,timeRanges:t})},onError:function(e){var t,r={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=i.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)r.details=Z.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!n)r.errorAction=ki(!0);else if(e.name===fs&&0===i.sourceBufferCount)r.errorAction=ki(!0);else{var s=++i.appendErrors[a];i.warn("Failed ".concat(s,"/").concat(i.hls.config.appendErrorMaxRetry,' times to append segment in "').concat(a,'" sourceBuffer (').concat(n||"no media error",")")),(s>=i.hls.config.appendErrorMaxRetry||n)&&(r.fatal=!0)}i.hls.trigger(ee.ERROR,r)}};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(D,a,this.isPending(this.tracks[a]))}},{key:"getFlushOp",value:function(e,t,i){var r=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(i)),{label:"remove",execute:function(){r.removeExecutor(e,t,i)},onStart:function(){},onComplete:function(){r.hls.trigger(ee.BUFFER_FLUSHED,{type:e})},onError:function(n){r.warn("Failed to remove ".concat(t,"-").concat(i,' from "').concat(e,'" SourceBuffer'),n)}}}},{key:"onBufferFlushing",value:function(e,t){var i=this,r=t.type,n=t.startOffset,a=t.endOffset;r?this.append(this.getFlushOp(r,n,a),r):this.sourceBuffers.forEach(function(e){var t=p(e,1)[0];t&&i.append(i.getFlushOp(t,n,a),t)})}},{key:"onFragParsed",value:function(e,t){var i=this,r=t.frag,n=t.part,a=[],s=n?n.elementaryStreams:r.elementaryStreams;s[xe]?a.push("audiovideo"):(s[Ce]&&a.push("audio"),s[_e]&&a.push("video"));0===a.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(r.type," level: ").concat(r.level," sn: ").concat(r.sn)),this.blockBuffers(function(){var e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:r.stats;i.hls.trigger(ee.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})},a).catch(function(e){i.warn("Fragment buffered callback ".concat(e)),i.stepOperationQueue(i.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 i=p(t,1)[0];if(i){var r=e.tracks[i];if(r)return!r.ended||r.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var i,r=this;this.sourceBuffers.forEach(function(e){var i=p(e,1)[0];if(i){var n=r.tracks[i];t.type&&t.type!==i||(n.ending=!0,n.ended||(n.ended=!0,r.log("".concat(i," buffer reached EOS"))))}});var n=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,i=p(e,1)[0];return i&&!(null!=(t=r.tracks[i])&&t.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(function(){r.tracksEnded();var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream(),r.hls.trigger(ee.BUFFERED_TO_END,void 0)):e&&r.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 i=p(t,1)[0];if(null!==i){var r=e.tracks[i];r&&(r.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var i=t.details;i.fragments.length&&(this.details=i,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 i,r=null==(i=t.errorAction)?void 0:i.nextAutoLevel;X(r)&&r!==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,i=this.media;if(i&&null!==t&&this.sourceBufferCount){var r=e.config,n=i.currentTime,a=t.levelTargetDuration,s=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.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=r.frontBufferFlushThreshold;if(X(u)&&u>0){var c=Math.max(r.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,i){var r=this;this.sourceBuffers.forEach(function(e){var t=p(e,2),n=t[0],a=t[1];if(a){var s=ji.getBuffered(a);if(s.length>0&&i>s.start(0)){var o;r.hls.trigger(ee.BACK_BUFFER_REACHED,{bufferEnd:i});var l=r.tracks[n];if(null!=(o=r.details)&&o.live)r.hls.trigger(ee.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=l&&l.ended)return void r.log("Cannot flush ".concat(n," back buffer while SourceBuffer is in ended state"));r.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}})}},{key:"flushFrontBuffer",value:function(e,t,i){var r=this;this.sourceBuffers.forEach(function(t){var n=p(t,2),a=n[0],s=n[1];if(s){var o=ji.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(i>u||e>=u&&e<=c)return;r.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,i=this.mediaSource;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,r)}}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 r>(X(i.duration)?i.duration:0)&&r>s||!X(s)?{duration:r}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,i=e.start,r=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!==i&&void 0!==r&&(this.log("MediaSource duration is set to ".concat(n.duration,". Setting seekable range to ").concat(i,"-").concat(r,".")),n.setLiveSeekableRange(i,r)))}},{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,i=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(Kt(i))),this.tracksReady){var r,n=null==(r=this.transferData)?void 0:r.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(i){var r=p(i,2),n=r[0],a=r[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 i=p(t,1)[0];e.executeNext(i)})}else{var i=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:i,reason:i.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in e){var n=r,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=i.addSourceBuffer(o),u=ps(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 i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&vt(i,"video")&&(r=function(e,t){var i=[];if(e)for(var r=e.split(","),n=0;n<r.length;n++)ft(r[n],"video")||i.push(r[n]);return t&&i.push(t),i.join(",")}(r,i));var n=St(r,e.levelCodec);return n?"audio"===t.slice(0,5)?kt(n,this.appendSource):n:""}},{key:"trackSourceBuffer",value:function(e,t){var i=this,r=t.buffer;if(r){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,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 r=t.removedRanges;null!=r&&r.length&&i.hls.trigger(ee.BUFFER_FLUSHED,{type:e})})}}},{key:"mediaSrc",get:function(){var e,t,i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.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 i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var i,r=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(null==(i=this.mediaSource)?void 0:i.readyState));this.error("".concat(r),t),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});var n=this.currentOp(e);n&&n.onError(r)}},{key:"updateTimestampOffset",value:function(e,t,i,r,n,a){var s=t-e.timestampOffset;Math.abs(s)>=i&&(this.log("Updating ".concat(r," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(n," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,i){var r=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!r||!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(r.duration)?r.duration:1/0,l=X(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(i,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 i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new vs("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));i.ending=!1,i.ended=!1,r.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=p(e,2),i=t[0],r=t[1];return i&&r.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var i=p(t,1)[0];return i&&!!e.currentOp(i)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"blockBuffers",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!i.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var r=this.operationQueue,n=i.map(function(e){return t.appendBlocker(e)});return i.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(function(i){r===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var i,r=null==(i=t.tracks[e])?void 0:i.buffer;r&&!r.updating&&t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}},{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,i){return t+(e.isPending(e.tracks[i])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(p(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return p(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,i){var r=this.tracks[e];if(r){var n=r.buffer;if(n){var a=i.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var i=t.buffer;i&&(t.listeners.forEach(function(e){i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}}])}(ve);function ms(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function ps(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 i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.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 i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.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,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(i,": ").concat(e[i].height,"p@").concat(e[i].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(t){var i=this,r=this.hls.levels;if(!r.length)return-1;var n=r.filter(function(e,r){return i.isLevelAllowed(e)&&r<=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 i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.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,i){if(null==e||!e.length)return-1;for(var r=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=Math.max(t,i),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&r(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"},Ts={HLS:"h"},ks=o(function e(t,i){a(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=i});function Ss(e,t,i,r){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(i),{cause:r});var n}function As(e,t,i){return Ss("serialize",e,t,i)}var bs=o(function e(t){a(this,e),this.description=t}),Ls="Bare Item";function Is(e){if(!1===ArrayBuffer.isView(e))throw As(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,T(t)))),":");var t}function Rs(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw As(e,"Integer");return e.toString()}function ws(e,t){if(e<0)return-ws(-e,t);var i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){var r=Math.floor(e*i);return(r%2==0?r:r+1)/i}return Math.round(e*i)/i}function Ps(e){var t=ws(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw As(e,"Decimal");var i=t.toString();return i.includes(".")?i:"".concat(i,".0")}var Ds=/[\x00-\x1f\x7f]+/;function Cs(e){var t,i=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw As(i,"Token");return i}function _s(e){switch(S(e)){case"number":if(!X(e))throw As(e,Ls);return Number.isInteger(e)?Rs(e):Ps(e);case"string":return function(e){if(Ds.test(e))throw As(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return Cs(e);case"boolean":return function(e){if("boolean"!=typeof e)throw As(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 bs)return Cs(e);default:throw As(e,Ls)}}function xs(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw As(e,"Key");return e}function Ms(e){return null==e?"":Object.entries(e).map(function(e){var t=p(e,2),i=t[0],r=t[1];return!0===r?";".concat(xs(i)):";".concat(xs(i),"=").concat(_s(r))}).join("")}function Os(e){return e instanceof ks?"".concat(_s(e.value)).concat(Ms(e.params)):_s(e)}function Fs(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==S(e)||null==e)throw As(e,"Dict");var i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map(function(e){var t=p(e,2),i=t[0],r=t[1];r instanceof ks==!1&&(r=new ks(r));var n,a=xs(i);return!0===r.value?a+=Ms(r.params):(a+="=",Array.isArray(r.value)?a+="(".concat((n=r).value.map(Os).join(" "),")").concat(Ms(n.params)):a+=Os(r)),a}).join(",".concat(r))}function Ns(e,t){return Fs(e,t)}var Bs="CMCD-Object",Us="CMCD-Request",Gs="CMCD-Session",Vs="CMCD-Status",Hs={br:Bs,ab:Bs,d:Bs,ot:Bs,tb:Bs,tpb:Bs,lb:Bs,tab:Bs,lab:Bs,url:Bs,pb:Us,bl:Us,tbl:Us,dl:Us,ltc:Us,mtp:Us,nor:Us,nrr:Us,rc:Us,sn:Us,sta:Us,su:Us,ttfb:Us,ttfbb:Us,ttlb:Us,cmsdd:Us,cmsds:Us,smrt:Us,df:Us,cs:Us,ts:Us,cid:Gs,pr:Gs,sf:Gs,sid:Gs,st:Gs,v:Gs,msd:Gs,bs:Vs,bsd:Vs,cdn:Vs,rtp:Vs,bg:Vs,pt:Vs,ec:Vs,e:Vs},Ks=Us;function js(e,t){var i={};if(!e)return i;var r,n=Object.keys(e),a=t?(r=t,Object.keys(r).reduce(function(e,t){var i;return null===(i=r[t])||void 0===i||i.forEach(function(i){return e[i]=t}),e},{})):{};return n.reduce(function(t,i){var r,n=Hs[i]||a[i]||Ks;return(null!==(r=t[n])&&void 0!==r?r:t[n]={})[i]=e[i],t},i)}var Ws="event";var qs=function(e){return Math.round(e)},Ys=function(e,t){return Array.isArray(e)?e.map(function(e){return Ys(e,t)}):e instanceof ks&&"string"==typeof e.value?new ks(Ys(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;for(var n=i.pathname.split("/").slice(1),a=r.pathname.split("/").slice(1,-1);n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},zs=function(e){return 100*qs(e/100)},Xs={br:qs,d:qs,bl:zs,dl:zs,mtp:zs,nor:function(e,t){var i=e;return t.version>=2&&(e instanceof ks&&"string"==typeof e.value?i=new ks([e]):"string"==typeof e&&(i=[e])),Ys(i,t)},rtp:zs,tb:qs},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 io=["d","dl","nor","ot","rtp","su"];var ro=["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)||io.includes(e)||ro.includes(e)||to(e)}),Ws,function(e){return Js.includes(e)||Zs.includes(e)||to(e)}),Qs,function(e){return Js.includes(e)||io.includes(e)||to(e)});function oo(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};if(null==e||"object"!==S(e))return i;var r=t.version||e.v||1,n=t.reportingMode||Qs,a=1===r?ao:so[n],s=Object.keys(e).filter(a),o=t.filter;"function"==typeof o&&(s=s.filter(o));var l=n===$s||n===Ws;l&&!s.includes("ts")&&s.push("ts"),r>1&&!s.includes("v")&&s.push("v");var u=de({},Xs,t.formatters),c={version:r,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===r)return;n=r}"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 bs(n)),i[t]=n))}),i}function lo(e,t,i){return de(e,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};if(!e)return i;var r=js(oo(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(r).reduce(function(e,t){var i=p(t,2),r=i[0],n=Ns(i[1],{whitespace:!1});return n&&(e[r]=n),e},i)}(t,i))}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,i){var r=function(e){if(!e)return"";var t=uo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return"".concat("CMCD","=").concat(t)}(t,i);if(!r)return e;if(co.test(e))return e.replace(co,r);var n=e.includes("?")?"&":"?";return"".concat(e).concat(n).concat(r)}var fo=function(){return o(function e(t){var i=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(){i.initialized&&(i.starved=!0),i.buffering=!0},this.onPlaying=function(){i.initialized||(i.initialized=!0),i.buffering=!1},this.applyPlaylistData=function(e){try{i.apply(e,{ot:Es.MANIFEST,su:!i.initialized})}catch(e){i.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var t=e.frag,r=e.part,n=i.hls.levels[t.level],a=i.getObjectType(t),s={d:1e3*(r||t).duration,ot:a};a!==Es.VIDEO&&a!==Es.AUDIO&&a!=Es.MUXED||(s.br=n.bitrate/1e3,s.tb=i.getTopBandwidth(a)/1e3,s.bl=i.getBufferLength(a));var o=r?i.getNextPart(r):i.getNextFrag(t);null!=o&&o.url&&o.url!==t.url&&(s.nor=o.url),i.apply(e,s)}catch(e){i.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=t;var r=this.config=t.config,n=r.cmcd;null!=n&&(r.pLoader=this.createPlaylistLoader(),r.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 i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}},{key:"createData",value:function(){var e;return{v:1,sf:Ts.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 i=t.ot===Es.INIT||t.ot===Es.VIDEO||t.ot===Es.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var r=this.includeKeys;r&&(t=Object.keys(t).reduce(function(e,i){return r.includes(i)&&(e[i]=t[i]),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,i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){var r=e.sn-i.startSN;return i.fragments[r+1]}}},{key:"getNextPart",value:function(e){var t,i=e.index,r=e.fragment,n=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=r.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===i&&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,i=0,r=this.hls;if(e===Es.AUDIO)t=r.audioTracks;else{var n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;t=r.levels.slice(0,a)}return t.forEach(function(e){e.bitrate>i&&(i=e.bitrate)}),i>0?i:NaN}},{key:"getBufferLength",value:function(e){var t=this.media,i=e===Es.AUDIO?this.audioBuffer:this.videoBuffer;return i&&t?1e3*ji.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,i=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new i(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,i,r){t(e),this.loader.load(e,i,r)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,i=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new i(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,i,r){t(e),this.loader.load(e,i,r)}}])}()}}])}(),vo=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["content-steering",e.logger])).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=e,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.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 i=t.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.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 i=t.errorAction;if((null==i?void 0:i.action)===fi&&i.flags===pi){var r=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&&r?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),t.details!==Z.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(r?r.length:r," priorities: ").concat(Kt(n)," penalized: ").concat(Kt(this.penalizedPathways))):i.resolved=!0}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var i=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(i,'"')),t=this.getLevelsForPathway(i),this.pathwayId=i}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 i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(function(e){r-i[e]>3e5&&delete i[e]});for(var n=0;n<e.length;n++){var a=e[n];if(!(a in i)){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,Zr(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,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),n=0;n<r.length;n++)if(t===re&&r[n].hasAudioGroup(e)||t===ne&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}},{key:"clonePathways",value:function(e){var t=this,i=this.levels;if(i){var r={},n={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!i.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new Ji(e.attrs);t["PATHWAY-ID"]=a;var i=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);i&&(r[t.AUDIO]=i,t.AUDIO=i),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=mo(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});i.push.apply(i,T(l)),go(t.audioTracks,r,o,a),go(t.subtitleTracks,n,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,i=this,r=this.hls.config,n=r.loader;this.loader&&this.loader.destroy(),this.loader=new n(r);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||r.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+a)}var s={responseType:"json",url:t.href},o=r.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,r,n,a){i.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){i.updated=performance.now(),i.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,t).href}catch(e){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}i.scheduleRefresh(i.uri||n.url),l&&i.clonePathways(l);var c={steeringManifest:s,url:t.toString()};i.hls.trigger(ee.STEERING_MANIFEST_LOADED,c),u&&i.updatePathwayPriority(u)}else i.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,r,n){if(i.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),i.stopLoad(),410===e.code)return i.enabled=!1,void i.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*i.timeToLoad;if(429!==e.code)i.scheduleRefresh(i.uri||t.url,a);else{var s=i.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}i.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,r){i.log("Timeout loading steering manifest (".concat(t.url,")")),i.scheduleRefresh(i.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var i,r=null==(i=t.hls)?void 0:i.media;!r||r.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},i)}}])}(ve);function go(e,t,i,r){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 Ji(a.attrs),a.url=a.attrs.URI=mo(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=r,a});e.push.apply(e,T(a))})}function mo(e,t,i,r){var n,a=r.HOST,s=r.PARAMS,o=r[i];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 po=function(e){function t(e){var i;return a(this,t),(i=n(this,t,["eme",e.logger])).hls=void 0,i.config=void 0,i.media=null,i.mediaResolved=void 0,i.keyFormatPromise=null,i.keySystemAccessPromises={},i._requestLicenseFailureCount=0,i.mediaKeySessions=[],i.keyIdToKeySessionPromise={},i.mediaKeys=null,i.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],i.bannedKeyIds={},i.onMediaEncrypted=function(e){var t=e.initDataType,r=e.initData,n='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(i.debug(n),null!==r){if(!i.keyFormatPromise){var a=Object.keys(i.keySystemAccessPromises);a.length||(a=Er(i.config));var s=a.map(yr).filter(function(e){return!!e});i.keyFormatPromise=i.getKeyFormatPromise(s)}i.keyFormatPromise.then(function(a){var s=pr(a);if("sinf"===t&&s===hr.FAIRPLAY){var o;try{var l=He(new Uint8Array(r)),u=it(or(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 i.warn("".concat(n," Failed to parse sinf: ").concat(e))}for(var c,d=be(o),h=i,f=h.keyIdToKeySessionPromise,v=h.mediaKeySessions,g=f[d],m=function(){var e=v[p],n=e.decryptdata;if(!n.keyId)return 0;var a=be(n.keyId);return rr(o,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(d)?(g=f[a])?(n.pssh||(delete f[a],n.pssh=new Uint8Array(r),n.keyId=o,(g=f[d]=g.then(function(){return i.generateRequestWithPreferredKeySession(e,t,r,"encrypted-event-key-match")})).catch(function(e){return i.handleError(e)})),1):0:void 0},p=0;p<v.length&&(0===(c=m())||1!==c);p++);g||i.handleError(new Error("Key ID ".concat(d," not encountered in playlist. Key-system sessions ").concat(v.length,".")))}else i.log('Ignoring "'.concat(e.type,'" event with init data type: "').concat(t,'" for selected key-system ').concat(s))}).catch(function(e){return i.handleError(e)})}},i.onWaitingForKey=function(e){i.log('"'.concat(e.type,'" event'))},i.hls=e,i.config=e.config,i.registerListeners(),i}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,i=t.drmSystems,r=t.widevineLicenseUrl,n=null==i?void 0:i[e];return n?n.licenseUrl:e===hr.WIDEVINE&&r?r: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,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]'))}},{key:"attemptKeySystemAccess",value:function(e){var t=this,i=this.hls.levels,r=function(e,t,i){return!!e&&i.indexOf(e)===t},n=i.map(function(e){return e.audioCodec}).filter(r),a=i.map(function(e){return e.videoCodec}).filter(r);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(i,r){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then(function(e){return i({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):r(t instanceof To?t:new To({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 i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function ".concat(i);return null===kr&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(r))}return i(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,i){var r,n=this,a=function(e,t,i,r){var n;switch(e){case hr.FAIRPLAY:n=["cenc","sinf"];break;case hr.WIDEVINE:case hr.PLAYREADY:n=["cenc"];break;case hr.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}}),videoCapabilities:i.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}})}]}(n,t,i,r)}(e,t,i,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(r=s)?void 0:r.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 i=n.fetchServerCertificate(e);n.log('Create media-keys for "'.concat(e,'"'));var r=l.mediaKeys=t.createMediaKeys().then(function(t){return n.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,i.then(function(i){return i?n.setMediaKeysServerCertificate(t,e,i):t})});return r.catch(function(t){n.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),r})}return o.then(function(){return s.mediaKeys})}},{key:"createMediaKeySessionContext",value:function(e){var t=e.decryptdata,i=e.keySystem,r=e.mediaKeys;this.log('Creating key-system session "'.concat(i,'" keyId: ').concat(be(t.keyId||[])," keyUri: ").concat(t.uri));var n=r.createSession(),a={decryptdata:t,keySystem:i,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}},{key:"renewKeySession",value:function(e){var t=e.decryptdata;if(t.pssh){var i=this.createMediaKeySessionContext(e),r=yo(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"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 i=e.mediaKeysSession;return this.log('Updating key-session "'.concat(i.sessionId,'" for keyId ').concat(be(e.decryptdata.keyId||[]),"\n } (data length: ").concat(t.byteLength,")")),i.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 yr(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var i=e.keySystem,r=e.mediaKeys;return t.attemptSetMediaKeys(i,r)})}},{key:"selectKeySystem",value:function(e){var t=this;return new Promise(function(i,r){t.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,n=yr(t);n?i(n):r(new Error('Unable to find format for key-system "'.concat(t,'"')))}).catch(r)})}},{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=Er(this.config),i=e.map(pr).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(i)}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,i=0;i<t.length;i++){var r=Eo(e,t[i]);if(r)return r}}},{key:"loadKey",value:function(e){var t=this,i=e.keyInfo.decryptdata,r=yo(i),n=this.bannedKeyIds[r];if(n||"internal-error"===this.getKeyStatus(i)){var a=ko(n||"internal-error",i);return this.handleError(a,e.frag),Promise.reject(a)}var s="(keyId: ".concat(r,' format: "').concat(i.keyFormat,'" method: ').concat(i.method," uri: ").concat(i.uri,")");this.log("Starting session for key ".concat(s));var o=this.keyIdToKeySessionPromise[r];if(!o){var l=this.getKeySystemForKeyPromise(i).then(function(r){var n=r.keySystem,a=r.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:i})})}).then(function(e){var r=i.pssh?i.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")});return l.catch(function(i){return t.handleError(i,e.frag)}),this.keyIdToKeySessionPromise[r]=l,l}return o.catch(function(r){if(r instanceof To){var n=fe({},r.data);"internal-error"===t.getKeyStatus(i)&&(n.decryptdata=i);var a=new To(n,r.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 To){t&&(e.data.frag=t);var i=e.data.decryptdata;this.error("".concat(e.message).concat(i?" (".concat(be(i.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),i=this.keyIdToKeySessionPromise[t];if(!i){var r=pr(e.keyFormat),n=r?[r]:Er(this.config);return this.attemptKeySystemAccess(n)}return i}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=Er(this.config)),0===e.length)throw new To({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 i=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var n=Promise.all(r).then(function(){return i.media?i.media.setMediaKeys(t):new Promise(function(e,r){i.mediaResolved=function(){if(i.mediaResolved=void 0,!i.media)return r(new Error("Attempted to set mediaKeys without media element attached"));i.mediaKeys=t,i.media.setMediaKeys(t).then(e).catch(r)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(function(){i.log('Media-keys set for "'.concat(e,'"')),r.push(n),i.setMediaKeysQueue=i.setMediaKeysQueue.filter(function(e){return-1===r.indexOf(e)})})}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,i,r){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,i,e);if(!o)throw new Error("Invalid response from configured generateRequest filter");t=o.initDataType,i=o.initData?o.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log('Skipping key-session request for "'.concat(r,'" (no initData)')),Promise.resolve(e);var l=yo(e.decryptdata),u=e.decryptdata.uri;this.log('Generating key-session request for "'.concat(r,'" keyId: ').concat(l," URI: ").concat(u," (init data type: ").concat(t," length: ").concat(i.byteLength,")"));var c=new Pn,d=e._onmessage=function(t){var i=e.mediaKeysSession;if(i){var r=t.messageType,n=t.message;a.log('"'.concat(r,'" message event for session "').concat(i.sessionId,'" message size: ').concat(n.byteLength)),"license-request"===r||"license-renewal"===r?a.renewLicense(e,n).catch(function(e){c.eventNames().length?c.emit("error",e):a.handleError(e)}):"license-release"===r?e.keySystem===hr.FAIRPLAY&&a.updateKeySession(e,lr("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(r,'"'))}else c.emit("error",new Error("invalid state"))},h=function(e,t){var i;t.keyStatus=e,e.startsWith("usable")?c.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=ko(e,t.decryptdata):"expired"===e?i=new Error("key expired (keyId: ".concat(l,")")):"released"===e?i=new Error("key released"):"status-pending"===e||a.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(l,")")),i&&(c.eventNames().length?c.emit("error",i):a.handleError(i))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){var i=a.getKeyStatuses(e);if(Object.keys(i).some(function(e){return"status-pending"!==i[e]})){if("expired"===i[l])return a.log("Expired key ".concat(Kt(i),' in key-session "').concat(e.mediaKeysSession.sessionId,'"')),void a.renewKeySession(e);var r=i[l];if(r)h(r,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(r="internal-error",e)}},1e3)),a.log("No status for keyId ".concat(l," (").concat(Kt(i),")."))}}}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,i).then(function(){a.log('Request generated for key-session "'.concat(e.mediaKeysSession.sessionId,'" keyId: ').concat(l," URI: ").concat(u))}).catch(function(t){throw new To({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,i={};return e.mediaKeysSession.keyStatuses.forEach(function(r,n){if("string"==typeof n&&"object"===S(r)){var a=n;n=r,r=a}var s="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===hr.PLAYREADY&&16===s.length){var o=be(s);i[o]=r,ur(s)}var l=be(s);"internal-error"===r&&(t.bannedKeyIds[l]=r),t.log('key status change "'.concat(r,'" for keyStatuses keyId: ').concat(l,' key-session "').concat(e.mediaKeysSession.sessionId,'"')),i[l]=r}),i}},{key:"fetchServerCertificate",value:function(e){var t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(n,a){var s={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,i,r){n(e.data)},onError:function(t,i,n,o){a(new To({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(r,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,i,n){a(new To({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(r,")")))},onAbort:function(e,t,i){a(new Error("aborted"))}};i.load(s,l,u)})):Promise.resolve()}},{key:"setMediaKeysServerCertificate",value:function(e,t,i){var r=this;return new Promise(function(n,a){e.setServerCertificate(i).then(function(a){r.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(i.byteLength,') on "').concat(t,'"')),n(e)}).catch(function(e){a(new To({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 i=this;return this.requestLicense(e,new Uint8Array(t)).then(function(t){return i.updateKeySession(e,new Uint8Array(t)).catch(function(t){throw new To({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 i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var r=(new DOMParser).parseFromString(i,"application/xml"),n=r.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=r.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return lr(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,i,r){var n=this,a=this.config.licenseXhrSetup;return a?Promise.resolve().then(function(){if(!i.decryptdata)throw new Error("Key removed");return a.call(n.hls,e,t,i,r)}).catch(function(s){if(!i.decryptdata)throw s;return e.open("POST",t,!0),a.call(n.hls,e,t,i,r)}).then(function(i){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}},{key:"requestLicense",value:function(e,t){var i=this,r=this.config.keyLoadPolicy.default;return new Promise(function(n,a){var s=i.getLicenseServerUrlOrThrow(e.keySystem);i.log("Sending license request to URL: ".concat(s));var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received ".concat(l instanceof ArrayBuffer?l.byteLength:l));var u=i.config.licenseResponseCallback;if(u)try{l=u.call(i.hls,o,s,e)}catch(e){i.error(e)}n(l)}else{var c=r.errorRetry,d=c?c.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>d||o.status>=400&&o.status<500)a(new To({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-i._requestLicenseFailureCount+1;i.warn("Retrying license request, ".concat(h," attempts left")),i.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,i.setupLicenseXHR(o,s,e,t).then(function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==hr.PLAYREADY&&(n=i.unpackPlayReadyKeyMessage(r,n)),r.send(n)}).catch(a)})}},{key:"onDestroying",value:function(){this.unregisterListeners(),this._clear()}},{key:"onMediaAttached",value:function(e,t){if(this.config.emeEnabled){var i=t.media;this.media=i,ln(i,"encrypted",this.onMediaEncrypted),ln(i,"waitingforkey",this.onWaitingForKey);var r=this.mediaResolved;r?r():this.mediaKeys=i.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,i=this;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};var r=this.mediaResolved;if(r&&r(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,br.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return i.removeSession(e)}).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch(function(e){i.log("Could not clear media keys: ".concat(e)),i.hls&&i.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){i.log("Could not close sessions and clear media keys: ".concat(e)),i.hls&&i.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&&i.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear()}},{key:"onManifestLoaded",value:function(e,t){var i=t.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(r.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(r)}}},{key:"removeSession",value:function(e){var t=this,i=e.mediaKeysSession,r=e.licenseXhr,n=e.decryptdata;if(i){this.log('Remove licenses and keys and close session "'.concat(i.sessionId,'" keyId: ').concat(be((null==n?void 0:n.keyId)||[]))),e._onmessage&&(i.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.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),i.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 i.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 be(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}po.CDMCleanupPromise=void 0;var To=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,[i])).data=void 0,e.error||(e.error=new Error(i)),r.data=e,e.err=e.error,r}return d(t,e),o(t)}(L(Error));function ko(e,t){var i="output-restricted"===e,r=i?Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new To({type:J.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},i?"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 i=this.hls.config;if(i.capLevelOnFPSDrop){var r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,i){var r=performance.now();if(t){if(this.lastTime){var n=r-this.lastTime,a=i-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(ee.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:i}),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=r,this.lastDroppedFrames=i,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 Ao(e,t){var i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function bo(e,t){var i=e.mode;if("disabled"===i&&(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(i){Te.debug("[texttrack-utils]: ".concat(i));try{var r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){Te.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(e))}}"disabled"===i&&(e.mode=i)}function Lo(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===i&&(e.mode=i)}function Io(e,t,i,r){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,i){var r=[],n=function(e,t){if(t<=e[0].startTime)return 0;var i=e.length-1;if(t>e[i].endTime)return-1;var r,n=0,a=i;for(;n<=a;)if(t<e[r=Math.floor((a+n)/2)].startTime)a=r-1;else{if(!(t>e[r].startTime&&n<i))return r;n=r+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<=i)r.push(o);else if(o.startTime>i)return r}return r}(e.cues,t,i),s=0;s<a.length;s++)r&&!r(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}function Ro(e){for(var t=[],i=0;i<e.length;i++){var r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}var wo=function(e){function t(e){var i;return a(this,t),(i=n(this,t,[e,"subtitle-track-controller"])).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var e=null,t=Ro(i.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}var n=i.findTrackForTextTrack(e);i.subtitleTrack!==n&&i.setSubtitleTrack(n)}},i.registerListeners(),i}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 i=this.media;if(i){var r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!r)Ro(i.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 i=t.id,r=t.groupId,n=t.details,a=this.tracksInGroup[i];if(a&&a.groupId===r){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(i,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(r," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),i===this.trackId&&this.playlistLoaded(i,t,s)}else this.warn("Subtitle track with id:".concat(i," and group:").concat(r," 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 i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(function(e){return-1===(null==r?void 0:r.indexOf(e))})){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!i||-1!==i.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=Yt(s,a);if(o>-1)n=a[o];else{var l=Yt(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==i?void 0:i.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,i=this.selectDefaultTrack,r=0;r<t.length;r++){var n=t[r];if((!i||n.default)&&(i||e)&&(!e||zt(n,e)))return r}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,i=0;i<t.length;i++){if(us(t[i],e))return i}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 i=this.currentTrack;if(i&&zt(e,i))return i;var r=Yt(e,this.tracksInGroup);if(r>-1){var n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}if(i)return null;var a=Yt(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,i){E(t,"loadingPlaylist",this,3)([e,i]);var r=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,i),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(r,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.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:r,groupId:n,deliveryDirectives:i||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this.media;if(e){var t,i=Ro(e.textTracks),r=this.currentTrack;if(r&&((t=i.filter(function(e){return us(r,e)})[0])||this.warn('Unable to find subtitle TextTrack with name "'.concat(r.name,'" and language "').concat(r.lang,'"'))),[].slice.call(i).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 i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),r){var n=!!r.details&&!r.details.live;if(e!==this.trackId||r!==i||!n){this.log("Switching to subtitle-track ".concat(e)+(r?' "'.concat(r.name,'" lang:').concat(r.lang," group:").concat(r.groupId):""));var a=r.id,s=r.groupId,o=void 0===s?"":s,l=r.name,u=r.type,c=r.url;this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:c});var d=this.switchParams(r.url,null==i?void 0:i.details,r.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,i=e.length;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}var Do=.025,Co=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function _o(e,t,i){return"".concat(e.identifier,"-").concat(i+1,"-").concat(Po(t))}var xo=function(){return o(function e(t,i){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=i,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 i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)}},{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)<Do))},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"]?Co.Range:Co.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))<Do)?t.start:t.start+t.duration}function Oo(e,t,i){var r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function Fo(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function No(e){var t=e.timelineStart,i=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+i).toFixed(2),"]")}var Bo=function(){return o(function e(t,i,r,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(i);this.interstitial=r,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 i=t.media;s.removeMediaListeners(),s.mediaAttached=i,s.interstitial.playoutLimit&&(i.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 i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=ji.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=i-.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=ji.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 i=t-this.startOffset;if(i>0&&i<e)return i}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 i=e-t;if(Math.abs(i)>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,i=this.duration;return Math.min(Math.max(0,e-t),i)}},{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,i){var r;null==(r=this.hls)||r.on(e,t)}},{key:"once",value:function(e,t,i){var r;null==(r=this.hls)||r.once(e,t)}},{key:"off",value:function(e,t,i){var r;null==(r=this.hls)||r.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":"")}}])}(),Uo=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,["interstitials-sched",i])).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=e,r}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(i,r){return e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i},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 i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(n=r[i])&&n.event;){var n;i--}return i}},{key:"findItemIndexAtTime",value:function(e,t){var i=this.items;if(i)for(var r=0;r<i.length;r++){var n=i[r];if(t&&"primary"!==t&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var i=this.items;if(i)for(var r=e;r<=t&&i[r];r++){var n=i[r].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var i=t.length;i--;){var r;if((null==(r=t[i].event)?void 0:r.identifier)===e)return i}return-1}},{key:"findAssetIndex",value:function(e,t){var i=e.assetList,r=i.length;if(r>1)for(var n=0;n<r;n++){var a=i[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===r-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 i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var i=this,r=e.main.details,n=r.dateRanges,a=this.events,s=this.parseDateRanges(n,{url:r.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 i=e.cue.pre,r=e.cue.post,n=t.cue.pre,a=t.cue.post;if(i&&!n)return-1;if(n&&!i)return 1;if(r&&!a)return 1;if(a&&!r)return-1;if(!(i||n||r||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){i.removeEvent(e)}),this.updateSchedule(e,l)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this.events||[];if(r.length||t.length||this.length<2){var n=this.items,a=this.parseSchedule(r,e);(i||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,i){for(var r=[],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 xo(o,t),this.eventMap[s]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r}},{key:"parseSchedule",value:function(e,t){var i=[],r=t.main.details,n=r.live?1/0:r.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,r){var l=t.cue.pre,u=t.cue.post,c=e[r-1]||null,d=t.appendInPlace,h=u?n:t.startOffset,f=t.duration,v=t.timelineOccupancy===Co.Range?f:0,g=t.resumptionOffset,m=(null==c?void 0:c.startTime)===h,p=h+t.cumulativeDuration,y=d?p+f:h+g;if(l||!u&&h<=0){var E=o;o+=v,t.timelineStart=p;var T=a;a+=f,i.push({event:t,start:p,end:y,playout:{start:T,end:a},integrated:{start:E,end:o}})}else{if(!(h<=n))return;if(!m){var k=h-s;if(k>.033){var S=s,A=o;o+=k;var b=a;a+=k;var L={previousEvent:e[r-1]||null,nextEvent:t,start:S,end:S+k,playout:{start:b,end:a},integrated:{start:A,end:o}};i.push(L)}else k>0&&c&&(c.cumulativeDuration+=k,i[i.length-1].end=h)}u&&(y=p),t.timelineStart=p;var I=o;o+=v;var R=a;a+=f,i.push({event:t,start:p,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,i.push({previousEvent:(null==(l=i[i.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{i.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 i}},{key:"setDurations",value:function(e,t,i){this.durations={primary:e,playout:t,integrated:i}}},{key:"resolveOffsets",value:function(e,t){var i=this,r=t.main.details,n=r.live?1/0:r.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;(i.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=ei(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(i.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&&i.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 i=this,r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>Do?(this.log('"'.concat(e.identifier,'" resumption ').concat(r," not aligned with estimated timeline end ").concat(n)),!1):!Object.keys(t).some(function(n){var a=t[n].details,s=a.edge;if(r>=s)return i.log('"'.concat(e.identifier,'" resumption ').concat(r," past ").concat(n," playlist end ").concat(s)),!1;var o=ei(null,a.fragments,r);if(!o)return i.log('"'.concat(e.identifier,'" resumption ').concat(r," 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-r)<Do+l||Math.abs(o.end-r)<Do+l)&&(i.log('"'.concat(e.identifier,'" resumption ').concat(r," 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,i=0,r=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+i;s.startOffset=i,s.timelineStart=o,r||(r=null===s.duration),n||(n=!!s.error),i+=s.error?0:s.duration||0}e.duration=r&&!n?Math.max(i,e.duration):i}}},{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 Vo=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 i,r=this,n=e.assetListUrl;try{i=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:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={responseType:"json",url:i.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,i,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,r.hls.trigger(ee.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=r.assignAssetListError(e,Z.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,i,a);r.hls.trigger(ee.ERROR,l)}},onError:function(t,i,n,a){var s=r.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(i.url,")")),i.url,a,n);r.hls.trigger(ee.ERROR,s)},onTimeout:function(t,i,n){var a=r.assignAssetListError(e,Z.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(i.url,")")),i.url,t,n);r.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,i,r,n,a){return e.error=i,{type:J.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:a,stats:n}}}])}();function Ho(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,i){var r;return a(this,t),(r=n(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&r.schedule){var t=e-r.timelinePos;if(!(Math.abs(t)<1/7056e5)){var i=t<=-.01;r.timelinePos=e,r.bufferedPos=e;var n=r.playingItem;if(n){if(i)r.schedule.resetErrorsInRange(e,e-t)&&r.updateSchedule(!0);if(r.checkBuffer(),i&&e<n.start||e>=n.end){var a,s=r.findItemIndex(n),o=r.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(i?-1:1),r.log("seeked ".concat(i?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!r.isInterstitial(n)&&null!=(a=r.media)&&a.paused&&(r.shouldPlay=!1),!i&&o>s){var l=r.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void r.setSchedulePosition(l)}r.setSchedulePosition(o)}else{var u=r.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(i&&e<d||e>=d+h)null!=(c=n.event)&&c.appendInPlace&&(r.clearAssetPlayers(n.event,n),r.flushFrontBuffer(e)),r.setScheduleToAssetAtTime(e,u)}else if(r.playingLastItem&&r.isInterstitial(n)){var f=n.event.assetList[0];f&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(e,f))}}}else r.checkBuffer()}}},r.onTimeupdate=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&e>r.timelinePos){r.timelinePos=e,e>r.bufferedPos&&r.checkBuffer();var t=r.playingItem;if(t&&!r.playingLastItem){if(e>=t.end){r.timelinePos=t.end;var i=r.findItemIndex(t);r.setSchedulePosition(i+1)}var n=r.playingAsset;if(n)e>=n.timelineStart+(n.duration||0)&&r.setScheduleToAssetAtTime(e,n)}}},r.onScheduleUpdate=function(e,t){var i=r.schedule;if(i){var n=r.playingItem,a=i.events||[],s=i.items||[],o=i.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&r.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return Go(e)})," pos: ").concat(r.timelinePos)),l.length&&r.log("Removed events ".concat(l));var c=null,d=null;n&&(c=r.updateItem(n,r.timelinePos),r.itemsMatch(n,c)?r.playingItem=c:r.waitingItem=r.endedItem=null),r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var h=r.bufferingItem;if(h&&(d=r.updateItem(h,r.bufferedPos),r.itemsMatch(h,d)?r.bufferingItem=d:h.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){r.clearAssetPlayer(e.identifier,null)})}),r.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(n){Math.abs(i)>Do&&r.warn("".concat(n,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(r.hls.trigger(ee.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),r.isInterstitial(n)&&l.includes(n.event.identifier))return r.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),void r.primaryFallback(n.event);n&&r.trimInPlace(c,n),h&&d!==c&&r.trimInPlace(d,h),r.checkBuffer()}}},r.hls=e,r.HlsPlayerClass=i,r.assetListLoader=new Vo(e),r.schedule=new Uo(r.onScheduleUpdate,e.logger),r.registerListeners(),r}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 i=this.media=t.media;ln(i,"seeking",this.onSeeking),ln(i,"timeupdate",this.onTimeupdate),ln(i,"play",this.onPlay),ln(i,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var n=this.findItemIndex(i);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 i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),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},i=function(t){return t?e.getAssetPlayer(t.identifier):t},r=function(t,r,a,s,o){if(t){var l=t[r].start,u=t.event;if(u){if("playout"===r||u.timelineOccupancy!==Co.Point){var c=i(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 i,r;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.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=i(e.playingAsset),m=(null==g?void 0:g.media)||e.primaryMedia;if(m){var p="primary"===n?m.currentTime:r(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-p,E=(f?p:m.currentTime)+y;if(E>=0&&(!g||f||E<=g.duration))return void(m.currentTime=E)}}if(c){var T=t;if("primary"!==n){var k=t-c[n].start;T=c.start+k}var S=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!S&&!c.event.appendInPlace){if(l){var A=e.findItemIndex(l);if(u>A){var b=e.schedule.findJumpRestrictedIndex(A+1,u);if(b>A)return void e.setSchedulePosition(b)}var L=0;if(S)e.timelinePos=T,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 D=e.media||(f?null==d?void 0:d.media:null);D&&(D.currentTime=T)}}}},o=function(){var i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;var r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){var i,n=t(),a=e.bufferingItem;return a&&a===n&&(r(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(i=e.bufferingAsset)?void 0:i.startOffset))||0},get currentTime(){var t=o(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){var i=o(),r=e.effectivePlayingItem;r&&r===i&&s(t+r.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,i=null==(t=o())?void 0:t.event.assetList;return i?i.map(function(t){return e.getAssetPlayer(t.identifier)}):[]},get playingIndex(){var t,i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.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 i=t();return e.findItemIndex(i)},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 r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(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,i){var r;if(0!==t&&"primary"!==i&&null!=(r=e.schedule)&&r.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[i].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){var r=e.findItemIndex(t);if(i.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(i,r,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,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var i=this.waitingItem||this.playingItem;if(!this.isInterstitial(i)||i.event.appendInPlace){var r=this.media;!r&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);var n=null==(t=r)?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 i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});var n=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(Kt(n))),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}},{key:"transferMediaTo",value:function(e,t){var i,r,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(i=this.detachedData)?void 0:i.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==(r=s.mediaSource)?void 0:r.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 m=l&&e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:!l||m,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 i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){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(r&&!this.playingItem){var l=e.findItemIndex(r);this.setSchedulePosition(l)}}}},{key:"advanceAssetBuffering",value:function(e,t){var i=e.event,r=i.findAssetIndex(t),n=Fo(i,r);if(i.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,i){var r=Fo(e,i);if(e.isAssetPastPlayoutLimit(r)){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[r];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(t,r)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var i=this.schedule;if(i){var r=t.parentIdentifier,n=i.getEvent(r);if(n){var a=i.findEventIndex(r),s=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;if(r&&!this.playbackDisabled){var n=e>=0?r[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:r.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:r.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,r,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,i,r,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 i=t.interstitial,r=s.findEventIndex(i.identifier);(r<e||r>e+1)&&a.clearInterstitial(i,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===i){var d=Fo(c,(i=s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,i);i=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,i);if(this.eventItemsMatch(o,h||r)||(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[i];if(!v)return void this.advanceAfterAssetEnded(c,e,i||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(i+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,i)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,i,t,e,l),this.shouldPlay&&Ho(f.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Ho(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.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,i){var r,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==(r=this.detachedData)||!r.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(i){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 i=e.start;if(this.primaryLive){var r=this.primaryDetails;if(0===t)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:ji.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Ko("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.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 i=this.hls.levels[t.level];if(i.details){var r=fe(fe({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(r){var n=fe(fe({},r),{},{audio:i});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{audio:i})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(r){var n=fe(fe({},r),{},{subtitles:i});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{subtitles:i})}},{key:"onAudioTrackSwitching",value:function(e,t){var i=qt(t);this.playerQueue.forEach(function(e){var r=e.hls;return r&&(r.setAudioOption(t)||r.setAudioOption(i))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var i=qt(t);this.playerQueue.forEach(function(e){var r=e.hls;return r&&(r.setSubtitleOption(t)||-1!==t.id&&r.setSubtitleOption(i))})}},{key:"onBufferCodecs",value:function(e,t){var i=t.tracks;i&&(this.requiredTracks=i)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var i=0;i<t.length;i++){var r=t[i];if(r.cue.post){var n,a=this.schedule.findEventIndex(r.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 i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;return e&&r&&r[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var i=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,r){e.event.isAssetPastPlayoutLimit(r)&&i.clearAssetPlayer(t.identifier,null)});var r=e.end+.25,n=ji.bufferInfo(this.primaryMedia,r,0);if(n.end>r||(n.nextStart||0)>r){this.log("trim buffered interstitial ".concat(Go(e)," (was ").concat(Go(t),")"));this.attachPrimary(r,null,!0),this.flushFrontBuffer(r)}}}},{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 i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.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],i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}},{key:"checkBuffer",value:function(e){var t,i=null==(t=this.schedule)?void 0:t.items;if(i){var r=ji.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}}},{key:"updateBufferedPos",value:function(e,t,i){var r=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&r)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=r.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 i&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var i=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var r=i.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,i=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,i)&&r){var n=r.items,a=r.events;if(!n||!a)return i;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:i?i.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(Go(e))+(i?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,i){var r=t.getAssetPlayer(e.identifier);r&&(i===u&&r.loadSource(),r.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 i}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;if(r)if(r.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),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}},{key:"bufferedToEvent",value:function(e,t){var i=e.event,r=0===i.assetList.length&&!i.assetListLoader,n=i.cue.once;if(r||!n){var a=this.preloadAssets(i,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var i=e.assetUrl,r=e.assetList.length,n=0===r&&!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(i?1:r," ").concat(e).concat(s?" live-start: ".concat(c," start-offset: ").concat(s):"")),i)return this.createAsset(e,0,0,o,e.duration,i);var h=this.assetListLoader.loadAssetList(e,s);h&&(e.assetListLoader=h)}else if(!a&&r){for(var f=t;f<r;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 m=e.assetList[t];if(m){var p=this.getAssetPlayer(m.identifier);return p&&p.loadSource(),p}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at ".concat(e)),Object.keys(i).forEach(function(i){t.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})}))}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,i=0;i<t.length;i++)if(e===t[i].assetId)return i;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 i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null}},{key:"createAsset",value:function(e,t,i,r,n,a){var s={parentIdentifier:e.identifier,identifier:_o(e,a,t),duration:n,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,i){var r=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 m=new Bo(this.HlsPlayerClass,v,e,t);this.playerQueue.push(m),e.assetList[i]=t;var p=!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=r.schedule)?void 0:a.findEventIndex(e.identifier))||-1;r.handleAssetItemError(o,e,l,i,s.message)}else{var u=n.edge-n.fragmentStart,c=t.duration;(p||null===c||u>c)&&(p=!1,r.log('Interstitial asset "'.concat(f,'" duration change ').concat(c," > ").concat(u)),t.duration=u,r.updateSchedule())}};m.on(ee.LEVEL_UPDATED,function(e,t){var i=t.details;return y(i)}),m.on(ee.LEVEL_PTS_UPDATED,function(e,t){var i=t.details;return y(i)}),m.on(ee.EVENT_CUE_ENTER,function(){return r.onInterstitialCueEnter()});var E=function(e,t){var i=r.getAssetPlayer(f);if(i&&t.tracks){i.off(ee.BUFFER_CODECS,E),i.tracks=t.tracks;var n=r.primaryMedia;r.bufferingAsset===i.assetItem&&n&&!i.media&&r.bufferAssetPlayer(i,n)}};m.on(ee.BUFFER_CODECS,E);m.on(ee.BUFFERED_TO_END,function(){var i,n=r.getAssetPlayer(f);if(r.log("buffered to end of asset ".concat(n)),n&&r.schedule){var a=r.schedule.findEventIndex(e.identifier),s=null==(i=r.schedule.items)?void 0:i[a];r.isInterstitial(s)&&r.advanceAssetBuffering(s,t)}});var T=function(t){return function(){if(r.getAssetPlayer(f)&&r.schedule){r.shouldPlay=!0;var i=r.schedule.findEventIndex(e.identifier);r.advanceAfterAssetEnded(e,i,t)}}};return m.once(ee.MEDIA_ENDED,T(i)),m.once(ee.PLAYOUT_LIMIT_REACHED,T(1/0)),m.on(ee.ERROR,function(t,n){if(r.schedule){var a=r.getAssetPlayer(f);if(n.details===Z.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void r.handleInPlaceStall(e):(r.onTimeupdate(),void r.checkBuffer(!0));r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,"Asset player error ".concat(n.error," ").concat(e))}}),m.on(ee.DESTROYING,function(){if(r.getAssetPlayer(f)&&r.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};r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(No(t))),this.hls.trigger(ee.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:m}),m}},{key:"clearInterstitial",value:function(e,t){this.clearAssetPlayers(e,t),e.reset()}},{key:"clearAssetPlayers",value:function(e,t){var i=this;e.assetList.forEach(function(e){i.clearAssetPlayer(e.identifier,t)})}},{key:"resetAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'.concat(e,'" after error'));var i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var i=this.getAssetPlayerQueueIndex(e);if(-1!==i){var r=this.playerQueue[i];this.log("clear ".concat(r," toSegment: ").concat(t?Go(t):t)),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,i,r,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,i[r]),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:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}},{key:"bufferAssetPlayer",value:function(e,t){var i,r;if(this.schedule){var n=e.interstitial,a=e.assetItem,s=this.schedule.findEventIndex(n.identifier),o=null==(i=this.schedule.items)?void 0:i[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==(r=this.detachedData)?void 0:r.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,i=this.primaryMedia;if(t&&i){var r=i.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||r-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(r,")")),o&&(l/i.playbackRate<.5||s.bufferedInPlaceToEnd(i))&&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,i,r,n){if(e.details!==Z.BUFFER_STALLED_ERROR){var a=t.assetList[r]||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:ki(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:i,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=r;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,i,r):h&&h.identifier===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,i=this.effectivePlayingItem,r=this.timelinePos;if(i){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(r," playing: ").concat(Go(i)," error: ").concat(e.error)),-1===r&&(r=this.hls.startPosition);var n=this.updateItem(i,r);this.itemsMatch(i,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===r)return void this.checkStart();if(this.schedule){var a=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(a)}}},{key:"onAssetListLoaded",value:function(e,t){var i,r,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(i=this.schedule)&&i.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var i=parseFloat(e.DURATION);n.createAsset(a,t,c,l+c,i,e.URI),c+=i}),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==(r=this.bufferingItem)?void 0:r.event;if(h){var v,g=this.schedule.findEventIndex(s),m=null==(v=this.schedule.items)?void 0:v[g];if(m){if(!this.playingItem&&this.timelinePos>m.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return a.error=new Error("Interstitial ".concat(o.length?"no longer within playback range":"asset-list is empty"," ").concat(this.timelinePos," ").concat(a)),this.log(a.error.message),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(m)}this.setSchedulePosition(g)}else if((null==f?void 0:f.identifier)===s){var p=a.assetList[0];if(p){var y=this.getAssetPlayer(p.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 i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break;case Z.BUFFER_STALLED_ERROR:var r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace)return void this.handleInPlaceStall(r.event);this.log("Primary player stall @".concat(this.timelinePos," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(ve),Wo=function(e){function t(e,i,r){var s;return a(this,t),(s=n(this,t,[e,i,r,"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,i){this.tracksBuffered=[],E(t,"onMediaDetaching",this,3)([e,i])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var i=t.frag,r=t.success;if(this.fragContextChanged(i)||(Oe(i)&&(this.fragPrevious=i),this.state=hn),r){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=i.start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=i.start+i.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}}},{key:"onBufferFlushing",value:function(e,t){var i=t.startOffset,r=t.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var n=r-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(i,n,oe)}}},{key:"onError",value:function(e,t){var i=t.frag;(null==i?void 0:i.type)===oe&&(t.details===Z.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dn&&(this.state=hn))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var i=this,r=t.subtitleTracks;this.levels&&os(this.levels,r)?this.levels=r.map(function(e){return new Gt(e)}):(this.tracksBuffered=[],this.levels=r.map(function(e){var t=new Gt(e);return i.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 i;if(this.currentTrackId=t.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==dn&&this.setInterval(500)}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var i,r=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!=(i=o.details)&&i.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&&zr(a,l=d.start);else a.hasProgramDateTime&&u.hasProgramDateTime?(on(a,u),l=a.fragmentStart):d&&zr(a,l=d.start);u&&!this.startFragRequested&&this.setStartPosition(u,l)}if(o.details=a,this.levelLastLoaded=o,s===r)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)ei(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,i=e.frag,r=e.payload,n=i.decryptdata,a=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=n&&n.key&&n.iv&&ar(n.method)){var s=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,sr(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:i}),e}).then(function(e){var t=performance.now();a.trigger(ee.FRAG_DECRYPTED,{frag:i,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,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,n=this.getLoadPosition(),a=ji.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),s=a.end,o=a.len,l=i.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=r.maxFragLookUpTolerance,g=s>d-v?0:v;!(h=ei(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,i.details)))return;var m=u[h.sn-l.startSN-1];if(m&&m.cc===h.cc&&this.fragmentTracker.getState(m)===Si&&(h=m),this.fragmentTracker.getState(h)===Si){var p=this.mapToInitFragWhenRequired(h);p&&this.loadFragment(p,i,s)}}}else this.state=hn}},{key:"loadFragment",value:function(e,i,r){Oe(e)?E(t,"loadFragment",this,3)([e,i,r]):this._loadInitSegment(e,i)}},{key:"mediaBufferTimeRanges",get:function(){return new qo(this.tracksBuffered[this.currentTrackId]||[])}}])}(An),qo=o(function e(t){a(this,e),this.buffered=void 0;var i=function(e,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(i,") is greater than the maximum bound (").concat(r,")"));return t[i][e]};this.buffered={get length(){return t.length},end:function(e){return i("end",e,t.length)},start:function(e){return i("start",e,t.length)}}}),Yo={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(Yo[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"],il=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 i="function"==typeof t?t():t;Te.log("".concat(this.time," [").concat(e,"] ").concat(i))}}}])}(),rl=function(e){for(var t=[],i=0;i<e.length;i++)t.push(e[i].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"],i=0;i<t.length;i++){var r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}},{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 i=0;i<Qo;i++)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 i=this.pos+1;i<t+1;i++)this.chars[i].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 i=zo(e);this.pos>=Qo?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+i+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(i,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,i=0;i<Qo;i++){var r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}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 i=0;i<Xo;i++)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,i=0;i<Xo;i++)if(!this.rows[i].equals(e.rows[i])){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 i=0;i<Xo;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[r].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[r+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,i=this.rows.splice(t,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),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=[],i="",r=-1,n=0;n<Xo;n++){var a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),ll=function(){return o(function e(t,i,r){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=i,this.mode=null,this.verbose=0,this.displayedMemory=new ol(r),this.nonDisplayedMemory=new ol(r),this.lastOutputScreen=new ol(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r},[{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,i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return r+": "+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 i=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}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,i,r){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 il;this.channels=[null,new ll(t,i,n),new ll(t+1,r,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 i=this;this.logger.time=e;for(var r=function(e){var r=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===r&&0===n)return 0;i.logger.log(3,function(){return"["+rl([t[e],t[e+1]])+"] -> ("+rl([r,n])+")"});var o=i.cmdHistory;if(r>=16&&r<=31){if(function(e,t,i){return i.a===e&&i.b===t}(r,n,o))return cl(null,null,o),i.logger.log(3,function(){return"Repeated command ("+rl([r,n])+") is dropped"}),0;cl(r,n,i.cmdHistory),(a=i.parseCmd(r,n))||(a=i.parseMidrow(r,n)),a||(a=i.parsePAC(r,n)),a||(a=i.parseBackgroundAttributes(r,n))}else cl(null,null,o);if(!a&&(s=i.parseChars(r,n))){var l=i.currentChannel;if(l&&l>0)i.channels[l].insertChars(s);else i.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||i.logger.log(2,function(){return"Couldn't parse cleaned data "+rl([r,n])+" orig: "+rl([t[e],t[e+1]])})},n=0;n<t.length;n+=2)r(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 i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}},{key:"parseMidrow",value:function(e,t){var i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+rl([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var r=e<=23?1:2;i=t>=64&&t<=95?1===r?$o[e]:Zo[e]:1===r?Jo[e]:el[e];var n=this.channels[r];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)}},{key:"interpretPAC",value:function(e,t){var i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}},{key:"parseChars",value:function(e,t){var i,r,n=null,a=null;(e>=25?(i=2,a=e-8):(i=1,a=e),a>=17&&a<=19)?(r=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+zo(r)+"' in channel "+i}),n=[r]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,function(){return"Char codes = "+rl(n).join(",")}),n}},{key:"parseBackgroundAttributes",value:function(e,t){var i;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=tl[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(r),!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 i=this.channels[t];i&&i.cueSplitAtTime(e)}}}])}();function cl(e,t,i){i.a=e,i.b=t}var dl=function(){if(null!=dr&&dr.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function n(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];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="",m=!0,p="auto",y="start",E=50,T="middle",k=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 r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return p},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=r(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 T},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return k},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");k=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(e){var t=r(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,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}var i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[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,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,i){for(var r=0;r<i.length;++r)if(t===i[r]){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 i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}])}();function gl(e,t,i,r){var n=r?e.split(r):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(i);if(2===s.length)t(s[0],s[1])}}var ml=new dl(0,0,""),pl="middle"===ml.align?"middle":"center";function yl(e,t,i){var r=e;function n(){var t=fl(e);if(null===t)throw new Error("Malformed timestamp: "+r);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'): "+r);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var r=new vl;gl(e,function(e,t){var n;switch(e){case"region":for(var a=i.length-1;a>=0;a--)if(i[a].id===t){r.set(e,i[a].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),r.integer(e,n[0]),r.percent(e,n[0])&&r.set("snapToLines",!1),r.alt(e,n[0],["auto"]),2===n.length&&r.alt("lineAlign",n[1],["start",pl,"end"]);break;case"position":n=t.split(","),r.percent(e,n[0]),2===n.length&&r.alt("positionAlign",n[1],["start",pl,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",pl,"end","left","right"])}},/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");var n=r.get("line","auto");"auto"===n&&-1===ml.line&&(n=-1),t.line=n,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",pl);var a=r.get("position","auto");"auto"===a&&50===ml.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 Tl=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 i(){var e=t.buffer,i=0;for(e=El(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;var r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}function r(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=i()).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=i(),t.state){case"HEADER":/:/.test(n)?r(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}}])}(),kl=/\r\n|\n\r|\n|\r/g,Sl=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return e.slice(i,i+t.length)===t};function Al(e,t,i){return Po(e.toString())+Po(t.toString())+Po(i)}function bl(e,t,i,r,n,a,s){var o,l=new Tl,u=Ae(new Uint8Array(e)).trim().replace(kl,"\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=i[r],s=i.ccOffset,l=(f-d)/9e4;if(null!=a&&a.new&&(void 0!==v?s=i.ccOffset=a.start:function(e,t,i){var r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(a=n)&&a.new;){var a;e.ccOffset+=r.start-n.start,r.new=!1,n=e[(r=n).prevCC]}e.presentationOffset=i}(i,r,l)),l){if(!t)return void(o=new Error("Missing initPTS for VTT MPEGTS"));s=l-i.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=Al(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)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(X(t)&&X(i)&&X(r)&&X(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*i,t+=6e4*r,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,i,r){var n=Ye(new Uint8Array(e),["mdat"]);if(0!==n.length){var a=n.map(function(e){return Ae(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 i(function(e,t){var i=(new DOMParser).parseFromString(e,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)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]=r.getAttribute("ttp:".concat(t))||n[t],e},{}),s="preserve"!==r.getAttribute("xml:space"),o=Cl(Dl(r,"styling","style")),l=Cl(Dl(r,"layout","region")),u=Dl(r,"body","[begin]");return[].map.call(u,function(e){var i=_l(e,s);if(!i||!e.hasAttribute("begin"))return null;var r=Ol(e.getAttribute("begin"),a),n=Ol(e.getAttribute("dur"),a),u=Ol(e.getAttribute("end"),a);if(null===r)throw Ml(e);if(null===u){if(null===n)throw Ml(e);u=r+n}var c=new dl(r-t,u-t,i);c.id=Al(c.startTime,c.endTime,c.text);var d=function(e,t,i){var r="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&&i.hasOwnProperty(s)&&(n=i[s]);return a.reduce(function(i,a){var s=xl(t,r,a)||xl(e,r,a)||xl(n,r,a);return s&&(i[a]=s),i},{})}(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){r(e)}}else r(new Error("Could not parse IMSC1 mdat"))}function Dl(e,t,i){var r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Cl(e){return e.reduce(function(e,t){var i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function _l(e,t){return[].slice.call(e.childNodes).reduce(function(e,i,r){var n;return"br"===i.nodeName&&r?e+"\n":null!=(n=i.childNodes)&&n.length?_l(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function xl(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Ml(e){return new Error("Could not parse ttml timestamp ".concat(e))}function Ol(e,t){if(!e)return null;var i=fl(e);return null===i&&(Il.test(e)?i=function(e,t){var i=Il.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):Rl.test(e)&&(i=function(e,t){var i=Rl.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}var Fl=function(){return o(function e(t,i){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=i},[{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,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,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"),i=new Fl(this,"textTrack3"),r=new Fl(this,"textTrack4");this.cea608Parser1=new ul(1,e,t),this.cea608Parser2=new ul(3,i,r)}},{key:"addCues",value:function(e,t,i,r,n){for(var a=!1,s=n.length;s--;){var o=n[s],l=Gl(o[0],o[1],t,i);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],i),a=!0,l/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){var u=this.captionsTracks[e];this.Cues.newCue(u,t,i,r)}else{var c=this.Cues.newCue(null,t,i,r);this.hls.trigger(ee.CUES_PARSED,{type:"captions",cues:c,track:e})}}},{key:"onInitPtsFound",value:function(e,t){var i=this,r=t.frag,n=t.id,a=t.initPTS,s=t.timescale,o=t.trackId,l=this.unparsedVttFrags;n===ae&&(this.initPTS[r.cc]={baseTime:a,timescale:s,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach(function(e){i.initPTS[e.frag.cc]?i.onFragLoaded(ee.FRAG_LOADED,e):i.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 i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var n=i.textTracks[r];if(Ul(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,i=this.captionsTracks,r=this.media,n=t[e],a=n.label,s=n.languageCode,o=this.getExistingTrack(a,s);if(o)i[e]=o,Lo(i[e]),Ao(i[e],r);else{var l=this.createTextTrack("captions",a,s);l&&(l[e]=!0,i[e]=l)}}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}}},{key:"createTextTrack",value:function(e,t,i){var r=this.media;if(r)return r.addTextTrack(e,t,i)}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}},{key:"onMediaDetaching",value:function(e,t){var i=!!t.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach(function(e){Lo(r[e]),delete r[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 i=0;i<t.length;i++)Lo(t[i])}}},{key:"onSubtitleTracksUpdated",value:function(e,t){var i=this,r=t.subtitleTracks||[],n=r.some(function(e){return e.textCodec===Ll});if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(os(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var a=this.media,s=a?Ro(a.textTracks):null;if(this.tracks.forEach(function(e,t){var r;if(s){for(var n=null,a=0;a<s.length;a++)if(s[a]&&Ul(s[a],e)){n=s[a],s[a]=null;break}n&&(r=n)}if(r)Lo(r);else{var o=Bl(e);(r=i.createTextTrack(o,e.name,e.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)}),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 i=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var r="textTrack".concat(t[1]),n=i.captionsProperties[r];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 i,r,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(i=null==(r=t.part)?void 0:r.index)?i:-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 i=t.frag,r=t.payload;if(i.type===oe)if(r.byteLength){var n=i.decryptdata,a="stats"in t;if(null==n||!n.encrypted||a){var s=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),s&&s.textCodec===Ll?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}},{key:"_parseIMSC1",value:function(e,t){var i=this,r=this.hls;Pl(t,this.initPTS[e.cc],function(t){i._appendCues(t,e.level),r.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},function(t){r.logger.log("Failed to parse IMSC1: ".concat(t)),r.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}},{key:"_parseVTTs",value:function(e){var t,i=this,r=e.frag,n=e.payload,a=this.initPTS,s=this.unparsedVttFrags,o=a.length-1;if(a[r.cc]||-1!==o){var l=this.hls;bl(null!=(t=r.initSegment)&&t.data?rt(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,function(e){i._appendCues(e,r.level),l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},function(t){var a="Missing initPTS for VTT MPEGTS"===t.message;a?s.push(e):i._fallbackToIMSC1(r,n),l.logger.log("Failed to parse VTT cue: ".concat(t)),a&&o>r.cc||l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})})}else s.push(e)}},{key:"_fallbackToIMSC1",value:function(e,t){var i=this,r=this.tracks[e.level];r.textCodec||Pl(t,this.initPTS[e.cc],function(){r.textCodec=Ll,i._parseIMSC1(e,t)},function(){r.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach(function(e){return bo(r,e)})}else{var n=this.tracks[t];if(!n)return;var a=n.default?"default":"subtitles"+t;i.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 i=t.frag,r=t.samples;if(i.type!==ae||"NONE"!==this.closedCaptionsForLevel(i))for(var n=0;n<r.length;n++){var a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,s[0]),this.cea608Parser2.addData(r[n].pts,s[1])}}}}},{key:"onBufferFlushing",value:function(e,t){var i=t.startOffset,r=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<r)){if(!a||"video"===a){var o=this.captionsTracks;Object.keys(o).forEach(function(e){return Io(o[e],i,r)})}if(this.config.renderTextTracksNatively&&0===i&&void 0!==n){var l=this.textTracks;Object.keys(l).forEach(function(e){return Io(l[e],i,n)})}}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],i=31&e[0],r=2,n=0;n<i;n++){var a=e[r++],s=127&e[r++],o=127&e[r++];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 Bl(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Ul(e,t){return!!e&&e.kind===Bl(t)&&us(t,e)}function Gl(e,t,i,r){return Math.min(t,r)-Math.max(e,i)}var Vl=/\s/,Hl={newCue:function(e,t,i,r){for(var n,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<r.rows.length;d++)if(s=!0,o=0,l="",!(n=r.rows[d]).isEmpty()){for(var h,f=0;f<n.chars.length;f++)Vl.test(n.chars[f].uchar)&&s?o++:(l+=n.chars[f].uchar,s=!1);n.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;var v=El(l.trim()),g=Al(t,i,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,i,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 bo(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||Wl,this.controller=new self.AbortController,this.stats=new De},[{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,i){var r=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 i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(de({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(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=i,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&X(u)?u:c,this.requestTimeout=self.setTimeout(function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))},t.timeout),(es(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(i){var a;r.response=r.loader=i;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(r.requestTimeout),t.timeout=c,r.requestTimeout=self.setTimeout(function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))},c-(o-n.loading.start)),!i.ok){var l=i.status,u=i.statusText;throw new ql(u||"fetch, bad network response",l,i)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var i=function(e){var t=Kl.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(X(i))return i}var r=e.get("Content-Length");if(r)return parseInt(r)}(i.headers)||n.total;var d=null==(a=r.callbacks)?void 0:a.onProgress;return d&&X(t.highWaterMark)?r.loadProgressively(i,n,e,t.highWaterMark,d):s?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(function(i){var a,s,l=r.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=i[o];u&&(n.loaded=n.total=u);var c={url:l.url,data:i,code:l.status},d=null==(a=r.callbacks)?void 0:a.onProgress;d&&!X(t.highWaterMark)&&d(n,e,i,l),null==(s=r.callbacks)||s.onSuccess(c,n,e,l)}).catch(function(t){var i;if(self.clearTimeout(r.requestTimeout),!n.aborted){var a=t&&t.code||0,s=t?t.message:null;null==(i=r.callbacks)||i.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,i){var r=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,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<r||a.dataLength?(a.push(l),a.dataLength>=r&&n(t,i,a.flush().buffer,e)):n(t,i,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}();function Wl(e,t){return new self.Request(e.url,t)}var ql=function(e){function t(e,i,r){var s;return a(this,t),(s=n(this,t,[e])).code=void 0,s.details=void 0,s.code=i,s.details=r,s}return d(t,e),o(t)}(L(Error)),Yl=/^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 De,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,i){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=i,this.loadInternal()}},{key:"loadInternal",value:function(){var e=this,t=this.config,i=this.context;if(t&&i){var r=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===r&&!e.stats.aborted)return a(r,i.url)}).catch(function(t){if(e.loader===r&&!e.stats.aborted)return r.open("GET",i.url,!0),a(r,i.url)}).then(function(){e.loader!==r||e.stats.aborted||e.openAndSendXhr(r,i,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:r.status,text:t.message},i,r,n)}):this.openAndSendXhr(r,i,t)}}},{key:"openAndSendXhr",value:function(e,t,i){e.readyState||e.open("GET",t.url,!0);var r=t.headers,n=i.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(r)for(var o in r)e.setRequestHeader(o,r[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),i.timeout=a&&X(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,i=this.stats;if(e&&t){var r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),4===r)){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;i.loading.end=Math.max(self.performance.now(),i.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;i.loaded=i.total=c,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(i,e,o,t);var h={url:t.responseURL,data:o,code:a};return void(null==(u=this.callbacks)||u.onSuccess(h,i,e,t))}}var f,v=n.loadPolicy.errorRetry;if(ci(v,i.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else Te.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,i)}}}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(ci(e,this.stats.retry,!0))this.retry(e);else{var t;Te.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}}},{key:"retry",value:function(e){var t=this.context,i=this.stats;this.retryDelay=li(e,i.retry),i.retry++,Te.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==t?void 0:t.url,", retrying ").concat(i.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&&Yl.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:Ti,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:kr,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:Hl,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:Wo,subtitleTrackController:wo,timelineController:Nl,audioStreamController:as,audioTrackController:cs,emeController:po,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,i){return t[i]=Ql(e[i]),t},{}):e}function $l(e,t){var i=e.loader;i!==jl&&i!==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,i){var r;return a(this,t),(r=n(this,t,["gap-controller",e.logger])).hls=void 0,r.fragmentTracker=void 0,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var e;null!=(e=r.media)&&e.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var e;r.hls&&(r.ended=(null==(e=r.media)?void 0:e.currentTime)||1,r.hls.trigger(ee.MEDIA_ENDED,{stalled:!1}))},r.hls=e,r.fragmentTracker=i,r.registerListeners(),r}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 i=this.media=t.media;ln(i,"playing",this.onMediaPlaying),ln(i,"waiting",this.onMediaWaiting),ln(i,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var i=this.media;i&&(un(i,"playing",this.onMediaPlaying),un(i,"waiting",this.onMediaWaiting),un(i,"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 i,r,n=null==(i=this.hls)?void 0:i.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(ji.getBuffered(a).length){var c=ji.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 m=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!d)return;var p=Math.max(d,c.start||0)-e,y=!(null==m||!m.live)?2*m.targetduration:2,E=tu(e,h);if(p>0&&(p<=y||E))return void(a.paused||this._trySkipBufferHole(E))}var T=n.detectStallWithCurrentTimeMs,k=self.performance.now(),S=this.waiting,A=this.stalled;if(null===A){if(!(S>0&&k-S<T))return void(this.stalled=k);A=this.stalled=S}var b=k-A;if(!s&&(b>=T||S)&&this.hls){var L;if("ended"===(null==(L=this.mediaSource)?void 0:L.readyState)&&(null==m||!m.live)&&Math.abs(e-((null==m?void 0:m.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=ji.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(I,b,e)}else this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(i),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(ee.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){var n=ji.bufferedInfo(ji.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=ji.timeRangesToArray(r),s=ji.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=ji.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=ji.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,i){var r,n,a=this.fragmentTracker,s=this.media,o=null==(r=this.hls)?void 0:r.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=tu(i,a);if(u||null!=l&&l.live&&i<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,i);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<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 i=this.fragmentTracker,r=e.nextStart;if(i&&r){var n=i.getFragAtPos(t,ae),a=i.getFragAtPos(r,ae);if(n&&a)return a.sn-n.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,i=this.media,r=this.stallReported,n=this.stalled;if(!r&&null!==n&&i&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(i.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,i=this.fragmentTracker,r=this.media,n=null==(t=this.hls)?void 0:t.config;if(!r||!i||!n)return 0;var a=r.currentTime,s=ji.bufferInfo(r,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&&r.readyState<3,c=o-a;if(c>0&&(l||u)){if(c>n.maxBufferHole){var d=!1;if(0===a){var h=i.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 m=tu(g,i);if(!m){v=!0;break}g+=m.duration}if(v)return 0}}var p=Math.max(o+.05,a+.1);if(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(p)),this.moved=!0,r.currentTime=p,null==e||!e.gap){var y=new Error("fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(p)),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 p}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,i=this.media,r=this.nudgeRetry,n=null==t?void 0:t.config;if(!i||!n)return 0;var a=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){var s=a+(r+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),i.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})}}}])}(Vi);function Zl(e,t){var i=eu(e.main);if(i&&i.start<=t)return i;var r=eu(e.audio);return r&&r.start<=t?r:null}function eu(e){if(!e)return null;switch(e.state){case hn:case dn:case En:case Tn:return null}return e.frag}function tu(e,t){return t.getAppendedFrag(e,ae)||t.getPartialFragment(e)}function iu(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ru(e,t,i,r,n){var a=new e(t,i,"");try{a.value=r,n&&(a.type=n)}catch(s){a=new e(t,i,Kt(n?fe({type:n},r):r))}return a}var nu=function(){var e=iu();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 i=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(){i.hls&&i.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 i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.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 i=e[t];if("metadata"===i.kind&&"id3"===i.label)return Ao(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var i=this.hls.config,r=i.enableEmsgMetadataCues,n=i.enableID3MetadataCues;if(r||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=iu();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==Zn.emsg||r)&&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=ru(s,c,d,f,l);v&&this.id3Track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var n=r.length;n--;){var a=r[n];a.type===t&&a.startTime<e&&a.endTime===nu&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var i=t.startOffset,r=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,i,r,"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 i=t.details;this.updateDateRangeCues(i,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var i=this;if(this.hls&&this.media){var r=this.hls.config,n=r.assetPlayerId,a=r.timelineOffset,s=r.enableDateRangeMetadataCues,o=r.interstitialsController;if(s){var l=iu();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=ru(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),m=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.cues)&&h.length)for(var p,y=Object.keys(m).filter(function(e){return!g.includes(e)}),E=function(){var e=y[T],t=null==(p=m[e])?void 0:p.cues;delete m[e],t&&Object.keys(t).forEach(function(e){var r=t[e];if(r){r.removeEventListener("enter",i.onEventCueEnter);try{f.removeCue(r)}catch(e){}}})},T=y.length;T--;)E();else m=this.dateRangeCuesAppended={};var k=e.fragments[e.fragments.length-1];if(0!==g.length&&X(null==k?void 0:k.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=g[A],t=v[e],r=t.startTime,n=m[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=r+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,i){if(i!==t.id){var r=v[i];if(r.class===t.class&&r.startDate>t.startDate&&(!e||t.startDate<e.startDate))return r}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var p=h[f];if(Zi(p)){var y=a[p];if(y)!s||null!=n&&n.durationKnown?Math.abs(y.startTime-r)>.01&&(y.startTime=r,y.endTime=u):y.endTime=u;else if(l){var E=t.attr[p];er(p)&&(E=Le(E));var T=ru(l,r,u,{key:p,data:E},Zn.dateRange);T&&(T.id=e,i.id3Track.addCue(T),a[p]=T,o&&("X-ASSET-LIST"!==p&&"X-ASSET-URL"!==p||T.addEventListener("enter",i.onEventCueEnter)))}}}m[e]={cues:a,dateRange:t,durationKnown:s}},A=0;A<g.length;A++)S()}}}}}}])}(),su=function(){return o(function e(t){var i=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=i.media,t=i.levelDetails;if(e&&t){i.currentTime=e.currentTime;var r=i.computeLatency();if(null!==r){i._latency=r;var n=i.config,a=n.lowLatencyMode,s=n.maxLiveSyncPlaybackRate;if(a&&1!==s&&t.live){var o=i.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(i.maxLatency,o+t.targetduration)&&l>.05&&i.forwardBufferLength>1){var u=Math.min(2,Math.max(1,s)),c=Math.round(2/(1+Math.exp(-.75*l-i.edgeStalled))*20)/20,d=Math.min(u,Math.max(1,c));i.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&i.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,i=e.partHoldBack,r=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*r);var c=r;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 i=this.levelDetails;if(null===i)return null;var r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,s=r-(this.config.lowLatencyMode&&i.partTarget||i.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 i=e.buffered.length;return(i?e.buffered.end(i-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 i=t.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onError",value:function(e,t){var i;t.details===Z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(r=this.targetLatency)?void 0:r.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,i){var r;return a(this,t),(r=n(this,t,[e,"level-controller"]))._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,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.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 i=this,r=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=kt(c,r)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),i=0;i<t.length;i++){var r=t[i].split(".");r.length>2&&"avc1"===r[0]&&(t[i]="avc1.".concat(parseInt(r[1]).toString(16)).concat(("000"+parseInt(r[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&&!i.isAudioSupported(c)||d&&!i.isVideoSupported(d))i.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'));else{var m=t.CODECS,p=t["FRAME-RATE"],y=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],T=t.RESOLUTION,k=t["VIDEO-RANGE"],S="".concat(E||".","-"),A="".concat(S).concat(e.bitrate,"-").concat(T,"-").concat(p,"-").concat(m,"-").concat(k,"-").concat(y);if(a[A])if(a[A].uri===e.url||e.attrs["PATHWAY-ID"])a[A].addGroupId("audio",t.AUDIO),a[A].addGroupId("text",t.SUBTITLES);else{var b=s[A]+=1;e.attrs["PATHWAY-ID"]=new Array(b+1).join(".");var L=i.createLevel(e);a[A]=L,n.push(L)}else{var I=i.createLevel(e);a[A]=I,s[A]=1,n.push(I)}}}),this.filterAndSortMediaOptions(n,t,o,l,u)}},{key:"createLevel",value:function(e){var t=new Gt(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(i.videoCodec,'"'));this.log(r.message),t.supportedResult=Pt(r,[])}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,i,r,n){var a,s=this,o=[],l=[],u=e,c=(null==(a=t.stats)?void 0:a.parsing)||{};if((i||r)&&n&&(u=u.filter(function(e){var t,i=e.videoCodec,r=e.videoRange,n=e.width,a=e.height;return(!!i||!(!n||!a))&&(!!(t=r)&&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",i=e;t.levels.length&&(i="one or more CODECS in variant not supported: ".concat(Kt(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,i){return i.indexOf(e)===t}))),s.warn(i),e+=" (".concat(i,")"));var r=new Error(e);s.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}),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(i&&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 r=pt(e.videoCodec),n=pt(t.videoCodec);if(r!==n)return n-r}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 m=h.bitrate,p=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(u.length," level(s) found, first bitrate: ").concat(m)),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){var y=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);y>p&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var E=n&&!r,T=this.hls.config,k=!(!T.audioStreamController||!T.audioTrackController),S={levels:u,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:k&&!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 i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)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(),i=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=i}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ie&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var i=t.frag;if(void 0!==i&&i.type===ae){var r=i.elementaryStreams;if(!Object.keys(r).some(function(e){return!!r[e]}))return;var n=this._levels[i.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 i,r,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(n)),void(null!=(r=t.deliveryDirectives)&&r.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!=(i=t.deliveryDirectives)&&i.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,i){E(t,"loadingPlaylist",this,3)([e,i]);var r=this.getUrlWithDirectives(e.uri,i),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==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(r)),this.hls.trigger(ee.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||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,i=this;if(1!==this._levels.length){var r=this._levels.filter(function(t,r){return r!==e||(i.steering&&i.steering.removeLevel(t),t===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});Zr(r),this._levels=r,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=r.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:r})}}},{key:"onLevelsUpdated",value:function(e,t){var i=t.levels;this._levels=i}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,i=e.maxAutoLevel,r=e.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(ee.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}])}(ss);function lu(e){var t={};e.forEach(function(e){var i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function uu(){return self.SourceBuffer||self.WebKitSourceBuffer}function cu(){if(!ke())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,i,r){var s;return a(this,t),(s=n(this,t,[e,i,r,"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 i=s.getFwdBufferInfoAtPos(e,t,ae,0);null!==i&&0!==i.len?s.tick():s.warn("Main forward buffer length at ".concat(t,' on "seeked" event ').concat(i?i.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 i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=r.startLevel;-1===n&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @".concat(i.toFixed(3))),e=i),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,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))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,i=this.levels,r=this.media;if(null!==t&&(r||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=i&&i[n]){var a=i[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)!==Li){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,m=u.fragments[g-1];m&&f.cc===m.cc&&(f=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var p=this.audioOnly&&!this.altAudio?Ce:_e,y=(p===_e?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p,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,i,r){var n=this.fragmentTracker.getState(e);n===Si||n===bi?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,i)):E(t,"loadFragment",this,3)([e,i,r]):this._loadInitSegment(e,i):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 i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.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;i=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(t.currentTime+i);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 pn:case yn:this.state=hn}this.nextLoadPosition=this.getLoadPosition()}},{key:"flushMainBuffer",value:function(e,i){E(t,"flushMainBuffer",this,3)([e,i,2===this.altAudio?"video":null])}},{key:"onMediaAttached",value:function(e,i){E(t,"onMediaAttached",this,3)([e,i]);var r=i.media;ln(r,"playing",this.onMediaPlaying),ln(r,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,i){var r=this.media;r&&(un(r,"playing",this.onMediaPlaying),un(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,E(t,"onMediaDetaching",this,3)([e,i]),!!i.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 i,r,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==(r=uu())||null==(i=r.prototype)?void 0:i.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 i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Sn)}}},{key:"onLevelLoaded",value:function(e,t){var i,r=this.levels,n=this.startFragRequested,a=t.level,s=t.details,o=s.totalduration;if(r){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!=(i=l.details)&&i.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,i=this.media;if(i){var r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==r&&i.duration>r&&(n<r||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.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(r.toFixed(3))),"buffered"===this.config.liveSyncMode){var u,c=ji.bufferInfo(i,r,0);if(null==(u=c.buffered)||!u.length)return void(i.currentTime=r);if(c.start<=n)return void(i.currentTime=r);var d=ji.bufferedInfo(c.buffered,n,0).nextStart;d&&(i.currentTime=d)}else i.currentTime=r}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,i=e.frag,r=e.part,n=e.payload,a=this.levels;if(a){var s=a[i.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(i.sn," of level ").concat(i.level," after level details were reset")),void this.fragmentTracker.removeFragment(i);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=i.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=r?r.index:-1,v=-1!==f,g=new Hi(i.level,i.sn,i.stats.chunkCount,n.byteLength,f,v),m=this.initPTS[i.cc];h.push(n,c,d,l,i,r,o.totalduration,u,g,m)}else this.warn("Level ".concat(i.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(i.sn," of level ").concat(i.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var i=this,r=this.hls,n=0!==this.altAudio;if($t(t.url,r))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.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(ee.BUFFER_FLUSHED,function(){i.hls&&i.hls.trigger(ee.AUDIO_TRACK_SWITCHED,t)}),void r.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(ee.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var i=$t(t.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()}},{key:"onBufferCreated",value:function(e,t){var i,r,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(r=s,i=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&i?(this.log("Alternate track found, use ".concat(r,".buffered to schedule main fragment loading")),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var i=t.frag,r=t.part,n=i.type===ae;if(n){if(this.fragContextChanged(i))return this.warn("Fragment ".concat(i.sn).concat(r?" p: "+r.index:""," of level ").concat(i.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===yn&&(this.state=hn));var a=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Oe(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var s=this.media;s&&(!this._hasEnoughToStart&&ji.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 i;if(t.fatal)this.state=Tn;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==(i=t.context)?void 0:i.type)!==ie||(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 i=t.type;if(i!==Ce||!this.altAudio){var r=(i===_e?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,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,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log("could not seek to ".concat(i,", already seeking at ").concat(t));var r=this.timelineOffset;r&&i&&(i+=r);var n=this.getLevelDetails(),a=ji.getBuffered(e),s=a.length?a.start(0):0,o=s-i,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")),i+=o,this.startPosition=i),t<i&&(this.log("seek to target start position ".concat(i," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=i)}}}},{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 i=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var r=i.hls,n=null==e?void 0:e.frag;if(n&&!i.fragContextChanged(n)){t.fragmentError=0,i.state=hn,i.startFragRequested=!1,i.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(ee.FRAG_LOADED,e),n.bitrateTest=!1}}).catch(function(t){i.state!==dn&&i.state!==Tn&&(i.warn(t),i.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,i=this.hls,r=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=r.video,c=r.text,d=r.id3,h=r.initSegment,f=l.details,v=this.altAudio?void 0:r.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=pn,h){var g=h.tracks;if(g){var m=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,m,n),i.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:t,tracks:g})}var p=h.initPTS,y=h.timescale,E=this.initPTS[s.cc];if(X(p)&&(!E||E.baseTime!==p||E.timescale!==y)){var T=h.trackId;this.initPTS[s.cc]={baseTime:p,timescale:y,trackId:T},i.trigger(ee.INIT_PTS_FOUND,{frag:s,id:t,initPTS:p,timescale:y,trackId:T})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var k=f.fragments[s.sn-1-f.startSN],S=s.sn===f.startSN,A=!k||s.cc>k.cc;if(!1!==r.independent){var b=u.startPTS,L=u.endPTS,I=u.startDTS,R=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:b,endPTS:L,startDTS:I,endDTS:R};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!A&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),P=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:b;if(!S&&P<D-this.config.maxBufferHole&&!A)return void this.backtrack(s);A&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,L,s.start,R,!0)}else S&&b-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,b,L,I,R),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,S||A)}else{if(!S&&!A)return void this.backtrack(s);s.gap=!0}}if(v){var C=v.startPTS,_=v.endPTS,x=v.startDTS,M=v.endDTS;o&&(o.elementaryStreams[Ce]={startPTS:C,endPTS:_,startDTS:x,endDTS:M}),s.setElementaryStreamInfo(Ce,C,_,x,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};i.trigger(ee.FRAG_PARSING_METADATA,O)}if(f&&c){var F={id:t,frag:s,details:f,samples:c.samples};i.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,i,r){var n=this;if(this.state===pn){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));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:i,part:null,chunkMeta:r,parent:i.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,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.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 i=e.currentTime;if(ji.isBuffered(e,i)?t=this.getAppendedFrag(i):ji.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;var r=this.fragPlaying,n=t.level;r&&t.sn===r.sn&&r.level===n||(this.fragPlaying=t,this.hls.trigger(ee.FRAG_CHANGED,{frag:t}),r&&r.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 i=this.getLevelDetails(),r=this.currentFrag||(i?ei(null,i.fragments,t):null);if(r){var n=r.programDateTime;if(null!==n){var a=n+1e3*(t-r.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}}])}(An),hu=function(e){function t(e,i){var r;return a(this,t),(r=n(this,t,["key-loader",i])).config=void 0,r.keyIdToKeyInfo={},r.emeController=null,r.config=e,r}return d(t,e),o(t,[{key:"abort",value:function(e){for(var t in this.keyIdToKeyInfo){var i=this.keyIdToKeyInfo[t].loader;if(i){var r;if(e&&e!==(null==(r=i.context)?void 0:r.frag.type))return;i.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,i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;return new Gi({type:J.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}},{key:"loadClear",value:function(e,t,i){var r=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)||!i&&s==o-1)return{v:r.emeController.selectKeySystemFormat(n).then(function(e){if(r.emeController){n.setKeyFormat(e);var t=pr(e);return t?r.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=Er(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(i){return t.loadInternal(e,i)}):this.loadInternal(e)}},{key:"loadInternal",value:function(e,t){var i,r;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!=(i=l)&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(r=l)&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(function(t){var i=t.keyInfo;return n.key=i.decryptdata.key,{frag:e,keyInfo:i}})}switch(this.log("".concat(this.keyIdToKeyInfo[o]?"Rel":"L","oading").concat(n.keyId?" keyId: "+be(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 i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&null!=(r=t.initSegment)&&r.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(be(a))),br.setKeyIdForUri(e.decryptdata.uri,a)):(a=br.addKeyIdForUri(e.decryptdata.uri),this.log("Generating keyId to patch media ".concat(be(a)))),e.decryptdata.keyId=a}}if(!e.decryptdata.keyId&&!Oe(t))return Promise.resolve(i);var s=this.emeController.loadKey(i);return(e.keyLoadPromise=s.then(function(t){return e.mediaKeySessionContext=t,i})).catch(function(i){throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i})}return Promise.resolve(i)}},{key:"loadKeyHTTP",value:function(e,t){var i=this,r=this.config,n=new(0,r.loader)(r);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=r.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:function(e,t,r,n){var o=r.frag,l=r.keyInfo,u=fu(l.decryptdata);if(!o.decryptdata||l!==i.keyIdToKeyInfo[u])return s(i.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,r,n,a){i.resetLoader(r),s(i.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,r,n){i.resetLoader(r),s(i.createKeyLoadError(t,Z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:function(e,r,n){i.resetLoader(r),s(i.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,i=e.keyInfo,r=e.url,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);var a=fu(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}])}(ve);function fu(e){if(e.keyFormat!==vr){var t=e.keyId;if(t)return be(t)}return e.uri}function vu(e){switch(e.type){case re:return se;case ne:return oe;default:return ae}}function gu(e,t){var i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}var mu=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,i=t.pLoader,r=t.loader,n=new(i||r)(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 i=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te,url:i,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var i=t.id,r=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ie,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var i=t.id,r=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:re,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var i=t.id,r=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:ne,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var i=this.loaders[ie];if(i){var r=i.context;r&&!t.levels.some(function(e){return e===r.levelOrTrack})&&(i.abort(),delete this.loaders[ie])}}},{key:"load",value:function(e){var t,i,r,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((i=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===ie&&null!==e.level?r=this.hls.levels[e.level].details:e.type===re&&null!==e.id?r=this.hls.audioTracks[e.id].details:e.type===ne&&null!==e.id&&(r=this.hls.subtitleTracks[e.id].details),r)){var u=r.partTarget,c=r.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);i=de({},i,{maxTimeToFirstByteMs:Math.min(d,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,i.maxTimeToFirstByteMs)})}}var h=i.errorRetry||i.timeoutRetry||{},f={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,i,r){var a=n.getInternalLoader(i);n.resetInternalLoader(i.type);var s=e.data;t.parsing.start=performance.now(),Cr.isMediaPlaylist(s)||i.type!==te?n.handleTrackOrLevelPlaylist(e,t,i,r||null,a):n.handleMasterPlaylist(e,t,i,r)},onError:function(e,t,i,r){n.handleNetworkError(t,i,!1,e,r)},onTimeout:function(e,t,i){n.handleNetworkError(t,i,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,i=t.autoStartLoad,r=t.startPosition,n=e.forceStartLoad;(i||n)&&(this.hls.logger.log("".concat(i?"auto":"force"," startLoad with configured startPosition ").concat(r)),this.hls.startLoad(r))}}},{key:"handleMasterPlaylist",value:function(e,t,i,r){var n=this,a=this.hls,s=e.data,o=gu(e,i),l=Cr.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,i,l.playlistParsingError,r,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 i=n.hls.config.preferManagedMediaSource,r=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];vt(o,"audio",i)?(e.audioCodec=r=r?"".concat(r,",").concat(o):o,ht.audio[r.substring(0,4)]=2,t.splice(s,1)):vt(o,"video",i)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,ht.video[a.substring(0,4)]=2,t.splice(s,1))}});var g=Cr.parseMasterPlaylistMedia(s,o,l),m=g.AUDIO,p=void 0===m?[]:m,y=g.SUBTITLES,E=g["CLOSED-CAPTIONS"];p.length&&(p.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"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ji({}),bitrate:0,url:""})));a.trigger(ee.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:y,captions:E,contentSteering:u,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:v})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,i,r,n){var a=this.hls,s=i.id,o=i.level,l=i.type,u=gu(e,i),c=X(o)?o:X(s)?s:0,d=vu(i),h=Cr.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===te){var f={attrs:new Ji({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Xr(h,0),a.trigger(ee.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=h,this.handlePlaylistLoaded(h,e,t,i,r,n)}},{key:"handleManifestParsingError",value:function(e,t,i,r,n){this.hls.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.MANIFEST_PARSING_ERROR,fatal:t.type===te,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})}},{key:"handleNetworkError",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,a="A network ".concat(i?"timeout":"error"+(r?" (status "+r.code+")":"")," occurred while loading ").concat(e.type);e.type===ie?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==re&&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=i?Z.MANIFEST_LOAD_TIMEOUT:Z.MANIFEST_LOAD_ERROR,l=!0;break;case ie:o=i?Z.LEVEL_LOAD_TIMEOUT:Z.LEVEL_LOAD_ERROR,l=!1;break;case re:o=i?Z.AUDIO_TRACK_LOAD_TIMEOUT:Z.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ne:o=i?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(r){var d=(null==t?void 0:t.url)||e.url;c.response=fe({url:d,data:void 0},r)}this.hls.trigger(ee.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,i,r,n,a){var s=this.hls,o=r.type,l=r.level,u=r.levelOrTrack,c=r.id,d=r.groupId,h=r.deliveryDirectives,f=gu(t,r),v=vu(r),g="number"==typeof r.level&&v===ae?l:void 0,m=e.playlistParsingError;if(m){if(this.hls.logger.warn("".concat(m," ").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:m,reason:m.message,response:t,context:r,level:g,parent:v,networkDetails:n,stats:i});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 ie:if(g)if(u){if(u!==s.levels[g]){var p=s.levels.indexOf(u);p>-1&&(g=p)}}else g=0;s.trigger(ee.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:o===te});break;case re:s.trigger(ee.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:h});break;case ne:s.trigger(ee.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:i,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:r,level:g,parent:v,networkDetails:n,stats:i})}}}])}(),pu=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 i=this.logger=function(e,t,i){var r=pe();if("object"===("undefined"==typeof console?"undefined":S(console))&&!0===e||"object"===S(e)){var n=["debug","log","info","warn","error"];n.forEach(function(t){r[t]=ye(t,e,i)});try{r.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.6.15"))}catch(e){return pe()}n.forEach(function(t){Ee[t]=ye(t,e)})}else de(Ee,r);return r}(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(e,t,i){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 r=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(i){var n="".concat(e,"Loading").concat(i),l=t[n];if(void 0!==l&&s){o.push(n);var u=r[a].default;switch(t[a]={default:u},i){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&&i.warn('hls.js config: "'.concat(o.join('", "'),'" setting(s) are deprecated, use "').concat(a,'": ').concat(Kt(t[a])))}),fe(fe({},r),t)}(e.DefaultConfig,t,i);this.userConfig=t,r.progressive&&$l(r,i);var n=r.abrController,s=r.bufferController,o=r.capLevelController,l=r.errorController,u=r.fpsController,c=new l(this),d=this.abrController=new n(this),h=new Ii(this),f=r.interstitialsController,v=f?this.interstitialsController=new f(this,e):null,g=this.bufferController=new s(this,h),m=this.capLevelController=new o(this),p=new u(this),y=new mu(this),E=r.contentSteeringController,T=E?new E(this):null,k=this.levelController=new ou(this,T),A=new au(this),b=new hu(this.config,this.logger),L=this.streamController=new du(this,h,b),I=this.gapController=new Jl(this,h);m.setStreamController(L),p.setStreamController(L);var R=[y,k,L];v&&R.splice(1,0,v),T&&R.splice(1,0,T),this.networkControllers=R;var w=[d,g,I,m,p,A,h];this.audioTrackController=this.createController(r.audioTrackController,R);var P=r.audioStreamController;P&&R.push(this.audioStreamController=new P(this,h,b)),this.subtitleTrackController=this.createController(r.subtitleTrackController,R);var D=r.subtitleStreamController;D&&R.push(this.subtititleStreamController=new D(this,h,b)),this.createController(r.timelineController,w),b.emeController=this.emeController=this.createController(r.emeController,w),this.cmcdController=this.createController(r.cmcdController,w),this.latencyController=this.createController(su,w),this.coreComponents=w,R.push(c);var C=c.onErrorOut;"function"==typeof C&&this.on(ee.ERROR,C,c),this.on(ee.MANIFEST_LOADED,y.onManifestLoaded,y)}return o(e,[{key:"createController",value:function(e,t){if(e){var i=new e(this);return t&&t.push(i),i}return null}},{key:"on",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,i)}},{key:"once",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,i)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,r=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,i,r)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,i){return this._emitter.emit(e,t,i)}},{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 i=e===ee.ERROR;this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:i,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 i="media"in e,r=i?e.media:e,n=i?e:{media:r};this._media=r,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,i=this._url,r=this._url=Pe.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(r)),t&&i&&(i!==r||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 i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}},{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(r){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(i+16*Math.random())%16|0;return i=Math.floor(i/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 xt.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 i=e.length,r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=r)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 Dt(e,Wt(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return Dn}},{key:"isMSESupported",value:function(){return cu()}},{key:"isSupported",value:function(){return function(){if(!cu())return!1;var e=ke();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(mt(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(mt(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return ke()}},{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}}])}();pu.defaultConfig=void 0;var yu="https://sspproxy.adstorm.co/openrtb2/auction/adstorm";function Eu(e){var t;void 0===e&&(e={});var i=!1,r=null!==(t=e.debug)&&void 0!==t&&t;function n(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r&&console.log.apply(console,M(["[Prebid]"],x(e),!1))}function a(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,M(["[Prebid]"],x(e),!1))}function s(){return D(this,void 0,void 0,function(){var e,t,s,o,l,u,c,d,h,f,v,g,m,p,y,E;return C(this,function(T){switch(T.label){case 0:if(!i)throw new Error("Prebid not initialized. Call initialize() first.");e=3e3,n("Fetching auction response from:",yu),t="undefined"!=typeof AbortController?new AbortController:null,s=setTimeout(function(){null==t||t.abort()},e+2e3),T.label=1;case 1:return T.trys.push([1,6,,7]),o={method:"POST"},t&&(o.signal=t.signal),[4,fetch(yu,o)];case 2:return l=T.sent(),clearTimeout(s),l.ok?[3,4]:[4,l.text().catch(function(){return""})];case 3:throw u=T.sent(),new Error("Prebid Server returned HTTP ".concat(l.status,": ").concat(u.slice(0,200)));case 4:return[4,l.json()];case 5:if(c=T.sent(),r&&(null===(y=null==c?void 0:c.ext)||void 0===y?void 0:y.responsetimemillis)&&n("Bidder response times:",c.ext.responsetimemillis),r&&(null===(E=null==c?void 0:c.ext)||void 0===E?void 0:E.errors)&&a("Auction errors:",c.ext.errors),d=function(e){var t,i,r,n,a,s,o,l,u=[],c=(null==e?void 0:e.seatbid)||[],d=(null==e?void 0:e.cur)||"USD";try{for(var h=_(c),f=h.next();!f.done;f=h.next()){var v=f.value,g=v.seat||"unknown",m=v.bid||[];try{for(var p=(r=void 0,_(m)),y=p.next();!y.done;y=p.next()){var E=y.value,T=null===(l=null===(o=null===(s=null===(a=E.ext)||void 0===a?void 0:a.prebid)||void 0===s?void 0:s.cache)||void 0===o?void 0:o.vastXml)||void 0===l?void 0:l.url,k=E.adm||void 0,S={bidder:g,cpm:E.price||0,width:E.w||0,height:E.h||0,adId:E.id||"",impId:E.impid||"",creativeId:E.crid||"",currency:d};T&&(S.vastUrl=T),k&&(S.vastXml=k),E.adomain&&(S.adomain=E.adomain),u.push(S)}}catch(e){r={error:e}}finally{try{y&&!y.done&&(n=p.return)&&n.call(p)}finally{if(r)throw r.error}}}}catch(e){t={error:e}}finally{try{f&&!f.done&&(i=h.return)&&i.call(h)}finally{if(t)throw t.error}}return u.sort(function(e,t){return t.cpm-e.cpm}),u}(c),n("Received ".concat(d.length," bid(s)")),r)try{for(h=_(d),f=h.next();!f.done;f=h.next())v=f.value,n(" ".concat(v.bidder,": $").concat(v.cpm.toFixed(2)," ").concat(v.currency)+" ".concat(v.width,"x").concat(v.height)+(v.vastUrl?" [cached VAST]":"")+(v.vastXml&&!v.vastUrl?" [VAST XML]":""))}catch(e){m={error:e}}finally{try{f&&!f.done&&(p=h.return)&&p.call(h)}finally{if(m)throw m.error}}return[2,d];case 6:if(g=T.sent(),clearTimeout(s),"AbortError"===(null==g?void 0:g.name))return a("Auction request timed out after ".concat(e+2e3,"ms")),[2,[]];throw g;case 7:return[2]}})})}return{initialize:function(){return D(this,void 0,void 0,function(){return C(this,function(e){return i||(i=!0,n("Initialized, auction URL:",yu)),[2]})})},requestBids:s,requestBidsUntilResponse:function(){return D(this,void 0,void 0,function(){var e,t,r,o;return C(this,function(l){switch(l.label){case 0:if(!i)throw new Error("Prebid not initialized. Call initialize() first.");t=function(t){var i,r,o;return C(this,function(l){switch(l.label){case 0:return l.trys.push([0,2,,3]),[4,s()];case 1:return(i=l.sent()).length>0?(n("requestBidsUntilResponse: got ".concat(i.length," bid(s) on attempt ").concat(t)),[2,{value:i}]):(n("requestBidsUntilResponse: no bids on attempt ".concat(t,"/").concat(3)),[3,3]);case 2:return r=l.sent(),e=r,a("requestBidsUntilResponse: attempt ".concat(t,"/").concat(3," failed:"),r),[3,3];case 3:return t<3?(n("requestBidsUntilResponse: waiting ".concat(o=1500*t,"ms before retry")),[4,new Promise(function(e){return setTimeout(e,o)})]):[3,5];case 4:l.sent(),l.label=5;case 5:return[2]}})},r=1,l.label=1;case 1:return r<=3?[5,t(r)]:[3,4];case 2:if("object"===S(o=l.sent()))return[2,o.value];l.label=3;case 3:return r++,[3,1];case 4:if(e instanceof Error)throw e;return[2,[]]}})})},destroy:function(){i=!1,n("Destroyed")},get isInitialized(){return i}}}function Tu(e){return"video/mp4"===e||e.includes("mp4")}function ku(e,t,i){var r,n,a,s;void 0===t&&(t="all"),void 0===i&&(i="[VastParser]");try{var o=(new DOMParser).parseFromString(e,"text/xml"),l=o.querySelector("parsererror");if(l)return console.error("".concat(i," XML parsing error (malformed VAST XML):"),l.textContent),null;var u=o.querySelector("Ad");if(!u)return console.warn("".concat(i," No Ad element found in VAST XML")),null;var c=u.getAttribute("id")||"unknown",d=(null===(r=o.querySelector("AdTitle"))||void 0===r?void 0:r.textContent)||"Ad",h="empty"===c||d.toLowerCase().includes("no ad available")||"no ad available"===d.toLowerCase(),f=((null===(n=o.querySelector("Duration"))||void 0===n?void 0:n.textContent)||"00:00:30").split(":"),v=3600*parseInt(f[0]||"0",10)+60*parseInt(f[1]||"0",10)+Math.round(parseFloat(f[2]||"0")),g=o.querySelectorAll("MediaFile"),m=[];if(console.log("".concat(i," Found ").concat(g.length," MediaFile element(s) in VAST XML")),g.forEach(function(e,r){var n,a=e.getAttribute("type")||"",s=(null===(n=e.textContent)||void 0===n?void 0:n.trim())||"",o=e.getAttribute("width")||"",l=e.getAttribute("height")||"";if(console.log("".concat(i," MediaFile ").concat(r,': type="').concat(a,'", url="').concat(s.substring(0,80),'...", width="').concat(o,'", height="').concat(l,'"')),s){var u=function(e){return"application/x-mpegURL"===e||e.includes("m3u8")}(a),c=Tu(a);if("hls-only"===t?u:"mp4-first"!==t||(c||u)){var d=e.getAttribute("bitrate"),h=d?parseInt(d,10):void 0;m.push({url:s,type:a,width:parseInt(o||"1920",10),height:parseInt(l||"1080",10),bitrate:h&&h>0?h:void 0}),console.log("".concat(i,' Added MediaFile: type="').concat(a,'" url="').concat(s.substring(0,80),'..."'))}else console.log("".concat(i," MediaFile ").concat(r,' ignored (type="').concat(a,'" not accepted by filter "').concat(t,'")'))}else console.warn("".concat(i," MediaFile ").concat(r," has empty URL"))}),"mp4-first"===t&&m.length>1&&m.sort(function(e,t){return(Tu(e.type)?0:1)-(Tu(t.type)?0:1)}),0===m.length)return h?console.warn("".concat(i," No ads available (VAST response indicates no ads)")):console.warn("".concat(i," No compatible media files found in VAST XML")),null;var p={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};o.querySelectorAll("Impression").forEach(function(e){var t,i=null===(t=e.textContent)||void 0===t?void 0:t.trim();i&&p.impression.push(i)}),o.querySelectorAll("Tracking").forEach(function(e){var t,i=e.getAttribute("event"),r=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(i&&r){var n=i;p[n]&&p[n].push(r)}});var y=null===(s=null===(a=o.querySelector("ClickThrough"))||void 0===a?void 0:a.textContent)||void 0===s?void 0:s.trim();return{id:c,title:d,duration:v,mediaFiles:m,trackingUrls:p,clickThrough:y}}catch(e){return console.error("".concat(i," Error parsing VAST XML:"),e),null}}function Su(e,t,i){void 0===i&&(i="[VastParser]"),e&&0!==e.length&&e.forEach(function(e){try{var r=e;if(t&&(r="".concat(r).concat(r.includes("?")?"&":"?","session_id=").concat(t)),"undefined"!=typeof fetch)(function(e){return D(this,arguments,void 0,function(e,t,i,r){var n,a,s;return void 0===t&&(t=2),void 0===i&&(i=500),void 0===r&&(r="[VastParser]"),C(this,function(o){switch(o.label){case 0:n=function(n){return C(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,6]),[4,fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache",keepalive:!0})];case 1:return a.sent(),[2,{value:void 0}];case 2:return a.sent(),n<t?[4,new Promise(function(e){return setTimeout(e,i*Math.pow(2,n))})]:[3,4];case 3:return a.sent(),[3,5];case 4:console.warn("".concat(r," Tracking pixel failed after ").concat(t+1," attempts: ").concat(e)),a.label=5;case 5:return[3,6];case 6:return[2]}})},a=0,o.label=1;case 1:return a<=t?[5,n(a)]:[3,4];case 2:if("object"===S(s=o.sent()))return[2,s.value];o.label=3;case 3:return a++,[3,1];case 4:return[2]}})})})(r,2,500,i).catch(function(){});else{var n=new Image(1,1);n.onerror=function(){},n.src=r}console.log("".concat(i," Fired tracking pixel: ").concat(r))}catch(e){console.warn("".concat(i," Error firing tracking pixel:"),e)}})}var Au="[PrebidAdLayer]";function bu(e,t){if(e.vastXml){var i=ku(e.vastXml,"mp4-first",t);return Promise.resolve(i)}return e.vastUrl?function(e){return D(this,arguments,void 0,function(e,t,i){var r,n;return void 0===t&&(t="all"),void 0===i&&(i="[VastParser]"),C(this,function(a){switch(a.label){case 0:return[4,fetch(e,{mode:"cors",credentials:"include",headers:{Accept:"application/xml, text/xml, */*"},referrerPolicy:"no-referrer-when-downgrade"})];case 1:if(!(r=a.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(r.statusText));return[4,r.text()];case 2:return n=a.sent(),console.log("".concat(i," VAST XML received")),console.log("".concat(i," VAST XML content (first 2000 chars):"),n.substring(0,2e3)),[2,ku(n,t,i)]}})})}(e.vastUrl,"mp4-first",t):Promise.resolve(null)}function Lu(e,t){var i,r,n,a,s,o,l,u=!1,c=!1,d=Math.max(0,Math.min(1,e.volume||1)),h=new Map,f=null==t?void 0:t.mainHlsInstance,v=null!==(i=null==t?void 0:t.continueLiveStreamDuringAds)&&void 0!==i&&i,g=null!==(r=null==t?void 0:t.debug)&&void 0!==r&&r,m=!1,p=!1,y={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function E(e,t){var i,r,n=h.get(e);if(n)try{for(var a=_(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("".concat(Au," Error in event listener for ").concat(e,":"),t)}}}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(i)throw i.error}}}function T(e){Su(e,l,Au)}function k(e){var t,i;if(0===e.length)throw new Error("No media files available");var r=e[0];if(1===e.length)return r;var n=function(){if(!(null==f?void 0:f.levels))return null;var e=f.currentLevel;if(-1===e||!f.levels[e]){var t=f.loadLevel;if(-1!==t&&f.levels[t]){var i=f.levels[t];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}return null}var r=f.levels[e];return{width:r.width||1920,height:r.height||1080,bitrate:r.bitrate||5e6}}();if(!n)return g&&console.log("".concat(Au," No main stream quality info, using first media file")),r;var a=e.map(function(e){var t=Math.abs(e.width-n.width)+Math.abs(e.height-n.height),i=1e3*(e.bitrate||5e3);return{file:e,score:2*t+Math.abs(i-n.bitrate)/1e3}});return a.sort(function(e,t){return e.score-t.score}),null!==(i=null===(t=a[0])||void 0===t?void 0:t.file)&&void 0!==i?i:r}function S(){n&&(n.addEventListener("timeupdate",function(){var e=o;if(e&&n){var t=n.currentTime/e.duration;t>=.25&&!y.firstQuartile&&(y.firstQuartile=!0,T(e.trackingUrls.firstQuartile)),t>=.5&&!y.midpoint&&(y.midpoint=!0,T(e.trackingUrls.midpoint)),t>=.75&&!y.thirdQuartile&&(y.thirdQuartile=!0,T(e.trackingUrls.thirdQuartile))}}),n.addEventListener("playing",function(){var e=o;e&&!y.start&&(y.start=!0,T(e.trackingUrls.start),g&&console.log("".concat(Au," Ad started playing")))}),n.addEventListener("ended",function(){p||!o||y.complete||(y.complete=!0,T(o.trackingUrls.complete),g&&console.log("".concat(Au," Ad completed")),function(){if(p)return;g&&console.log("".concat(Au," Handling ad completion"));u=!1,A(!1),s&&(s.style.display="none",s.style.pointerEvents="none");E("ad_impression"),E("content_resume")}())}),n.addEventListener("error",function(e){p||(console.error("".concat(Au," Ad video error:"),e),o&&T(o.trackingUrls.error),b())}),n.addEventListener("volumechange",function(){o&&n&&(n.muted?T(o.trackingUrls.mute):T(o.trackingUrls.unmute))}),n.addEventListener("pause",function(){o&&n&&!n.ended&&T(o.trackingUrls.pause)}),n.addEventListener("play",function(){o&&n&&n.currentTime>0&&T(o.trackingUrls.resume)}))}function A(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function b(){p||(g&&console.log("".concat(Au," Handling ad error")),u=!1,A(!1),s&&(s.style.display="none",s.style.pointerEvents="none"),E("ad_error"))}function L(){a&&(a.destroy(),a=void 0),n&&(n.pause(),n.removeAttribute("src"),n.load())}function I(e){var t;n&&("application/x-mpegURL"===(t=e).type||t.type.includes("m3u8")?function(e){n&&(g&&console.log("".concat(Au," Starting HLS playback: ").concat(e.url)),pu.isSupported()?(a&&(a.destroy(),a=void 0),(a=new pu({enableWorker:!0,lowLatencyMode:!1})).loadSource(e.url),a.attachMedia(n),a.on(pu.Events.MANIFEST_PARSED,function(){n.play().catch(function(e){console.error("".concat(Au," Error starting HLS ad playback:"),e),b()})}),a.on(pu.Events.ERROR,function(e,t){t.fatal&&b()})):n.canPlayType("application/vnd.apple.mpegurl")?(n.src=e.url,n.play().catch(function(e){console.error("".concat(Au," Error starting native HLS ad playback:"),e),b()})):(console.error("".concat(Au," HLS not supported on this platform")),b()))}(e):function(e){n&&(g&&console.log("".concat(Au," Starting native MP4 playback: ").concat(e.url)),n.src=e.url,n.load(),n.play().catch(function(e){console.error("".concat(Au," Error starting native ad playback:"),e),b()}))}(e))}return{initialize:function(){g&&console.log("".concat(Au," Initializing"))},updateOptions:function(e){var t;void 0!==e.continueLiveStreamDuringAds&&(v=e.continueLiveStreamDuringAds),void 0!==e.mainHlsInstance&&(f=null!==(t=e.mainHlsInstance)&&void 0!==t?t:void 0)},playAd:function(t){return D(this,void 0,void 0,function(){var i,r,a,h,f,p,b;return C(this,function(R){switch(R.label){case 0:return m?[2,Promise.reject(new Error("Layer has been destroyed"))]:0===t.length?[2,Promise.reject(new Error("No bids provided"))]:(i=t[0],g&&console.log("".concat(Au," Winning bid: ").concat(i.bidder," $").concat(i.cpm.toFixed(2)," ").concat(i.currency)),[4,bu(i,Au)]);case 1:return(r=R.sent())?(g&&console.log("".concat(Au," Ad parsed: ").concat(r.title,", duration: ").concat(r.duration,"s, mediaFiles: ").concat(r.mediaFiles.length)),l="session-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),o=r,y=w({},{impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1}),T(r.trackingUrls.impression),y.impression=!0,s||((a=document.createElement("div")).style.position="absolute",a.style.left="0",a.style.top="0",a.style.right="0",a.style.bottom="0",a.style.display="none",a.style.alignItems="center",a.style.justifyContent="center",a.style.pointerEvents="none",a.style.zIndex="10",a.style.backgroundColor="#000",null===(b=e.parentElement)||void 0===b||b.appendChild(a),s=a),n?L():((P=document.createElement("video")).style.position="absolute",P.style.left="0",P.style.top="0",P.style.width="100%",P.style.height="100%",P.style.objectFit="contain",P.style.backgroundColor="#000",P.playsInline=!0,P.muted=!1,P.volume=1,n=P,s.appendChild(n),S()),h=e.volume,d=Math.max(0,Math.min(1,h||d)),v||e.pause(),e.muted=!0,e.volume=0,u=!0,A(!0),f=c?1:d,n.volume=Math.max(0,Math.min(1,f)),n.muted=!1,s&&(s.style.display="flex",s.style.pointerEvents="auto"),E("content_pause"),p=k(r.mediaFiles),g&&console.log("".concat(Au," Loading ad from: ").concat(p.url)),I(p),[2]):(g&&console.warn("".concat(Au," Winning bid has no VAST URL or XML")),E("ad_error"),[2,Promise.reject(new Error("No VAST from bid"))])}var P})})},pause:function(){if(u&&n)try{n.paused||n.pause()}catch(e){g&&console.warn("".concat(Au," Error pausing ad:"),e)}},resume:function(){if(u&&n)try{n.paused&&n.play().catch(function(){})}catch(e){g&&console.warn("".concat(Au," Error resuming ad:"),e)}},stop:function(){return D(this,void 0,void 0,function(){return C(this,function(t){return p=!0,g&&console.log("".concat(Au," Stopping ad")),u=!1,A(!1),e.muted=c,e.volume=c?0:d,s&&(s.style.display="none",s.style.pointerEvents="none"),e.style.visibility="visible",e.style.opacity="1",v&&e.play().catch(function(){}),L(),n&&(n.pause(),n.removeAttribute("src"),n.load()),o=void 0,p=!1,[2]})})},destroy:function(){p=!0,g&&console.log("".concat(Au," Destroying")),m=!0,u=!1,A(!1),e.muted=c,e.volume=d,L(),n&&(n.pause(),n.removeAttribute("src"),n.remove(),n=void 0),(null==s?void 0:s.parentElement)&&s.parentElement.removeChild(s),s=void 0,o=void 0,h.clear()},isAdPlaying:function(){return u},resize:function(e,t){s&&(s.style.width="".concat(e,"px"),s.style.height="".concat(t,"px")),n&&(n.style.width="".concat(e,"px"),n.style.height="".concat(t,"px"))},on:function(e,t){h.has(e)||h.set(e,new Set),h.get(e).add(t)},off:function(e,t){var i;null===(i=h.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState:function(e,t){var i="number"!=typeof t||Number.isNaN(t)?d:Math.max(0,Math.min(1,t));c=e,d=i},getOriginalMutedState:function(){return c},getOriginalVolume:function(){return d},setAdVolume:function(e){n&&u&&(n.volume=Math.max(0,Math.min(1,e)))},getAdVolume:function(){return n&&u?n.volume:1},showPlaceholder:function(){var t;if(e.style.opacity="0",e.style.visibility="hidden",!s){var i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),s=i}s&&(s.style.display="flex",s.style.pointerEvents="auto")},hidePlaceholder:function(){s&&(s.style.display="none",s.style.pointerEvents="none"),u||(e.style.visibility="visible",e.style.opacity="1")}}}var Iu=null;function Ru(){var e,t,i,r,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="",m=!1,p=!1,y=!1;if(a.includes("Web0S")){f="LG",v="webOS",m=!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",m=!0,h="tv";var T=a.match(/Tizen\/([^\s]+)/),k=a.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=T?"Tizen ".concat(T[1]," ").concat(k).trim():"Tizen TV"}else a.includes("Philips")?(f="Philips",v="Saphi",m=!0,h="tv"):a.includes("Sharp")||a.includes("AQUOS")?(f="Sharp",v="Android TV",m=!0,h="tv"):a.includes("Android")&&(a.includes("Sony")||o.includes("Sony"))?(f="Sony",v="Android TV",m=!0,h="tv"):a.includes("Android")&&(a.includes("NetCast")||a.includes("LG"))?(f="LG",v="Android TV",m=!0,h="tv"):a.includes(" Roku")||a.includes("Roku/")?(f="Roku",v="Roku OS",m=!0,h="tv"):a.includes("AppleTV")&&(f="Apple",v="tvOS",m=!0,h="tv");if(a.includes("Android")){p=!0,v="Android",h=/Mobile/.test(a)?"mobile":"tablet",a.includes("Android")&&(0===l||a.includes("Google TV")||a.includes("XiaoMi"))&&(h="tv",m=!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")),p||m||/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===(i=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===i?void 0:i.angle),{brand:f,os:v,model:g||a.substring(0,50)+"...",deviceType:h,isSmartTV:m,isAndroid:p,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===(r=navigator.languages)||void 0===r?void 0:r.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function wu(e){return D(this,void 0,void 0,function(){var t,i,r,n,a,s,o,l,u,c,d,h,f;return C(this,function(v){switch(v.label){case 0:if(Iu)return[2,Iu];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(),i=void 0,"undefined"!=typeof TextEncoder)i=(new TextEncoder).encode(t);else{for(r=unescape(encodeURIComponent(t)),n=new Uint8Array(r.length),u=0;u<r.length;u++)n[u]=r.charCodeAt(u);i=n}return[4,crypto.subtle.digest("SHA-256",i)];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(""),Iu=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,Iu=(d+h+f).padEnd(64,"0")]}})})}var Pu="https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track";function Du(e,t){return D(this,void 0,void 0,function(){var i,r;return C(this,function(n){switch(n.label){case 0:return i={"Content-Type":"application/json"},e&&(i.Authorization="Bearer ".concat(e)),[4,fetch(Pu,{method:"POST",headers:i,body:JSON.stringify(t)})];case 1:if(!(r=n.sent()).ok)throw new Error("HTTP error! status: ".concat(r.status));return[4,r.json()];case 2:return n.sent(),[2]}})})}function Cu(e){return D(this,void 0,void 0,function(){var t,i,r,n,a,s;return C(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),[4,wu(t=Ru())];case 1:return i=o.sent(),r=w({browserId:i},t),n={"Content-Type":"application/json"},e&&(n.Authorization="Bearer ".concat(e)),[4,fetch(Pu,{method:"POST",headers:n,body:JSON.stringify(r)})];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]}})})}function _u(e,t){return D(this,void 0,void 0,function(){var i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,wu(i=Ru())];case 1:return r=s.sent(),n=w({browserId:r},i),[4,Du(e,w(w({},n),{licenseKey:e,adLoadedInfo:t}))];case 2:return s.sent(),[3,4];case 3:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending ad loaded tracking:",a),[3,4];case 4:return[2]}})})}function xu(e){return D(this,void 0,void 0,function(){var t,i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),[4,wu(Ru())];case 1:return t=s.sent(),i={browserId:t,timestamp:(new Date).toISOString()},r={"Content-Type":"application/json"},e&&(r.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:r,body:JSON.stringify(i)})];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]}})})}function Mu(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var r=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)&&(r[s]=a[s])}return r}),Array.from||(Array.from=function(e,t,i){var r=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var n=r.length>>>0,a=new Array(n),s=0;s<n;s++)a[s]=t?t.call(i,r[s],s):r[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 i=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){i.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,i=e.startsWith("?")?e.slice(1):e;i&&i.split("&").forEach(function(e){var i=x(e.split("="),2),r=i[0],n=i[1];if(r){var a=t.safeDecodeURIComponent(r),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 i=this.params.get(e)||[];i.push(String(t)),this.params.set(e,i)},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(i,r){i.forEach(function(i){e(i,r,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,i){t.forEach(function(t){e.push("".concat(encodeURIComponent(i),"=").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=[],i=0;i<e.length;i++){var r=e.charCodeAt(i);r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<55296||r>=57344?t.push(224|r>>12,128|r>>6&63,128|63&r):(i++,r=65536+((1023&r)<<10|1023&e.charCodeAt(i)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}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(i){return t.resolve(e()).then(function(){return i})},function(i){return t.resolve(e()).then(function(){throw i})})})}function Ou(){var e,t,i,r=navigator.userAgent,n=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"}(),a="Unknown",s="0",o=0,l=!1,u=!1,c=!0,d=!0,h="ima",f=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(r),v=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(r);if(i=f>0?f:void 0,/Web0S|webOS|LG Browser|LGSTB/i.test(r)){if(a="LG WebOS",l=!0,(g=r.match(/Web0S[/\s]*([\d.]+)/i)||r.match(/webOS[/\s]*([\d.]+)/i))&&g[1]||(g=r.match(/webOSTV[/\s-]*([\d.]+)/i)||r.match(/webOS\.TV[/\s-]*([\d.]+)/i)),g&&g[1])e=o=(m=(s=g[1]).split("."))[0]?parseInt(m[0],10):0;else f>0?f>=79?(e=6,s="6.0",o=6):f>=68?(e=5,s="5.0",o=5):f>=53?(e=4,s="4.0",o=4):f>=38?(e=3,s="3.0",o=3):(e=2,s="2.0",o=2):(s="Unknown",e=void 0);void 0!==e&&e>=4||f>=53?(c=!0,h="ima",u=!1):(c=!1,h="hls",u=!0)}else if(/Tizen/i.test(r)){var g,m;if(a="Samsung Tizen",l=!0,"Unknown"!==(s=(g=r.match(/Tizen[/\s]*([\d.]+)/i))&&g[1]?g[1]:"Unknown"))t=o=(m=s.split("."))[0]?parseInt(m[0],10):0;void 0!==t&&t>=4||void 0!==t&&t>=3&&f>=47||f>=53?(c=!0,h="ima",u=!1):(c=!1,h="hls",u=!0)}else/SMART-TV|SmartTV/i.test(r)?(a="Smart TV",l=!0,f>=53?(c=!0,h="ima"):(c=!1,h="hls",u=!0)):/NetCast/i.test(r)?(a="LG NetCast",l=!0,u=!0,c=!1,h="hls"):/BRAVIA/i.test(r)?(a="Sony BRAVIA",l=!0,f>=53?(c=!0,h="ima"):(c=!1,h="hls",u=!0)):(f>0&&(a="Chrome",s=f.toString(),o=f,f<50&&(c=!1,d=!1,h="hls")),v>0&&v<600&&(d=!1,f<50&&(c=!1,h="hls")));return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(d=!1,c=!1,h="hls"),"undefined"==typeof URLSearchParams&&(d=!1),{name:a,version:s,majorVersion:o,isSmartTV:l,isLegacyTV:u,platform:n,supportsIMA:c,supportsModernJS:d,recommendedAdPlayer:h,webOSVersion:e,tizenVersion:t,chromeVersion:i}}function Fu(){var e=Ou();if(e.isLegacyTV)return!1;if("undefined"==typeof document||"function"!=typeof document.createElement)return!1;try{if(!document.createElement("video"))return!1}catch(e){return!1}return"undefined"!=typeof Promise&&e.supportsIMA}function Nu(e){if(void 0===e&&(e=!1),e){var t=Ou(),i=Fu();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",w(w(w(w({browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsIMA:i,supportsModernJS:t.supportsModernJS,recommendedAdPlayer:t.recommendedAdPlayer},void 0!==t.webOSVersion?{webOSVersion:t.webOSVersion}:{}),void 0!==t.tizenVersion?{tizenVersion:t.tizenVersion}:{}),void 0!==t.chromeVersion?{chromeVersion:t.chromeVersion}:{}),{userAgent:navigator.userAgent}))}}function Bu(){var e={};return Ou().isSmartTV&&(e.allowNativeHls=!0),e}var Uu=function(){function e(e){this.pendingNextAdBids=null,this.continuousFetchLoopPromise=null,this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.adPodQueue=[],this.lastHeartbeatTime=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.showAds=!1,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.activeAdRequestToken=null,this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.continuousFetchingActive=!1,this.isInAdTransition=!1,this.maxPlaceholderDurationMs=5e3,this.isShowingPlaceholder=!1,this.totalAdRequestsInBreak=0,this.maxTotalAdRequestsPerBreak=20,this.pendingAdBreak=null,this.savedMutedStateBeforeScte=null,this.consecutiveFailures=0,this.maxConsecutiveFailures=5,this.lastAdRequestTime=0,this.minAdRequestIntervalMs=2500,this.backoffBaseMs=1e3,this.maxBackoffMs=15e3,this.adTransitionGapMs=1500,Mu();var t=Bu();this.config=w(w({},t),e),this.video=e.videoElement,Nu(e.debugAdTiming),this.prebidManager=Eu(void 0!==e.debugAdTiming?{debug:!!e.debugAdTiming}:{}),this.adLayer=Lu(this.video,{continueLiveStreamDuringAds:!1,debug:!!e.debugAdTiming})}return e.prototype.adRequest=function(){return D(this,void 0,void 0,function(){return C(this,function(e){switch(e.label){case 0:return[4,this.prebidManager.initialize()];case 1:return e.sent(),[2,this.prebidManager.requestBidsUntilResponse()]}})})},e.prototype.load=function(){return D(this,void 0,void 0,function(){var e,t,i=this;return C(this,function(r){switch(r.label){case 0:return this.attached||this.attach(),this.initializeTracking(),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 - VOD mode:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:"vod (main video pauses during ads)"}),this.adLayer.updateOptions({continueLiveStreamDuringAds:!1,mainHlsInstance:null}),this.config.autoplay?[4,null===(t=this.video.play())||void 0===t?void 0:t.catch(function(){})]:[3,2]):[3,3];case 1:r.sent(),r.label=2;case 2:return[2];case 3:return this.hls=new pu(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(pu.Events.MEDIA_ATTACHED,function(){var e;null===(e=i.hls)||void 0===e||e.loadSource(i.config.src)}),this.hls.on(pu.Events.MANIFEST_PARSED,function(e,t){return D(i,void 0,void 0,function(){var e,t,i,r,n,a,s,o;return C(this,function(l){switch(l.label){case 0:return!1===this.config.allowNativeHls?this.isLiveStream=!0:this.isLiveStream=null!==(n=null===(r=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===r?void 0:r.some(function(e){var t,i;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(i=null==e?void 0:e.details)||void 0===i?void 0:i.type)}))&&void 0!==n&&n,this.config.debugAdTiming&&(e=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})),this.adLayer.updateOptions({continueLiveStreamDuringAds:this.shouldContinueLiveStreamDuringAds(),mainHlsInstance:null!==(a=this.hls)&&void 0!==a?a:null}),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,t=null!==(s=this.config.minSegmentsBeforePlay)&&void 0!==s?s:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",t,"segments to buffer before playback"),0!==t&&this.config.autoplay?[3,2]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(o=this.video.play())||void 0===o?void 0:o.catch(function(){})]:[3,2]);case 1:l.sent(),l.label=2;case 2:return[2]}})})}),this.hls.on(pu.Events.LEVEL_LOADED,function(e,t){var r,n,a,s;if(!i.inAdBreak&&!i.pendingAdBreak){var o=null==t?void 0:t.details;if(o&&o.fragments&&0!==o.fragments.length)for(var l=Math.min(5,o.fragments.length),u=0;u<l;u++){var c=o.fragments[u],d=null==c?void 0:c.tagList;if(Array.isArray(d))try{for(var h=(r=void 0,_(d)),f=h.next();!f.done;f=h.next()){var v=f.value,g="",m="";if(Array.isArray(v))g=String(null!==(a=v[0])&&void 0!==a?a:""),m=String(null!==(s=v[1])&&void 0!==s?s:"");else if("string"==typeof v){var p=v.indexOf(":");p>=0?(g=v.substring(0,p),m=v.substring(p+1)):g=v}if(g&&(g.includes("EXT-X-CUE-OUT")||g.includes("EXT-X-DATERANGE"))){var y=g.includes("EXT-X-DATERANGE")?i.parseAttributeList(m):{};if(g.includes("EXT-X-CUE-OUT")||"SCTE35-OUT"in y||void 0!==y["SCTE35-OUT"]){var E=i.parseCueOutDuration(m),T=w(w({type:"start"},void 0!==E?{durationSeconds:E}:{}),{raw:{tag:g,value:m,earlyDetection:!0}});return i.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] 🎯 EARLY SCTE-35 DETECTION: Ad break marker found in fragment",u,"- starting pre-fetch (NOT playing yet)"),void i.startAdPrefetch(T,null==c?void 0:c.sn)}}}}catch(e){r={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(r)throw r.error}}}}}),this.hls.on(pu.Events.FRAG_BUFFERED,function(e,t){return D(i,void 0,void 0,function(){var e,t,i,r=this;return C(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.inAdBreak||this.adLayer.isAdPlaying()?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Ad break active — deferring play() to handleAdPodComplete().")),[3,3]):[3,1]:[3,3]):[3,3]);case 1:return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Starting playback.")),[4,null===(i=this.video.play())||void 0===i?void 0:i.catch(function(e){r.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})];case 2:n.sent(),n.label=3;case 3:return[2]}})})}),this.hls.on(pu.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 i.onId3Tag(e)})}),this.hls.on(pu.Events.FRAG_CHANGED,function(e,t){var r,n,a,s,o,l=null==t?void 0:t.frag,u=null==l?void 0:l.tagList;if(Array.isArray(u))try{for(var c=_(u),d=c.next();!d.done;d=c.next()){var h=d.value,f="",v="";if(Array.isArray(h))f=String(null!==(a=h[0])&&void 0!==a?a:""),v=String(null!==(s=h[1])&&void 0!==s?s:"");else if("string"==typeof h){var g=h.indexOf(":");g>=0?(f=h.substring(0,g),v=h.substring(g+1)):(f=h,v="")}if(f)if(f.includes("EXT-X-CUE-OUT-CONT")){var m=i.parseCueOutCont(v),p=w(w(w({type:"progress"},void 0!==(null==m?void 0:m.duration)?{durationSeconds:m.duration}:{}),void 0!==(null==m?void 0:m.elapsed)?{ptsSeconds:m.elapsed}:{}),{raw:{tag:f,value:v}});i.onScte35Marker(p)}else if(f.includes("EXT-X-CUE-OUT")){var y=i.parseCueOutDuration(v);p=w(w({type:"start"},void 0!==y?{durationSeconds:y}:{}),{raw:{tag:f,value:v}});i.onScte35Marker(p)}else if(f.includes("EXT-X-CUE-IN"))i.onScte35Marker({type:"end",raw:{tag:f,value:v}});else if(f.includes("EXT-X-DATERANGE")){var E=i.parseAttributeList(v),T="SCTE35-OUT"in E||void 0!==E["SCTE35-OUT"],k="SCTE35-IN"in E||void 0!==E["SCTE35-IN"],S=String(null!==(o=E.CLASS)&&void 0!==o?o:""),A=i.toNumber(E.DURATION);if(T||/com\.apple\.hls\.cue/i.test(S)){p=w(w({type:"start"},void 0!==A?{durationSeconds:A}:{}),{raw:{tag:f,value:v,attrs:E}});i.onScte35Marker(p)}k&&i.onScte35Marker({type:"end",raw:{tag:f,value:v,attrs:E}})}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(r)throw r.error}}}),this.hls.on(pu.Events.ERROR,function(e,t){var r,n;if(null==t?void 0:t.fatal)switch(t.type){case pu.ErrorTypes.NETWORK_ERROR:null===(r=i.hls)||void 0===r||r.startLoad();break;case pu.ErrorTypes.MEDIA_ERROR:null===(n=i.hls)||void 0===n||n.recoverMediaError();break;default:i.destroy()}}),this.hls.attachMedia(this.video),[2]}})})},e.prototype.getAdSource=function(){return"prebid"},e.prototype.attachAdLayerEventListeners=function(){var e=this;this.adLayer.on("ad_impression",function(){e.config.licenseKey&&function(e,t){D(this,void 0,void 0,function(){var i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,wu(i=Ru())];case 1:return r=s.sent(),n=w({browserId:r},i),[4,Du(e,w(w({},n),{licenseKey:e,adImpressionInfo:t}))];case 2:return s.sent(),[3,4];case 3:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending ad impression tracking:",a),[3,4];case 4:return[2]}})})}(e.config.licenseKey,{source:e.getAdSource(),adIndex:e.currentAdIndex,timestamp:(new Date).toISOString()})}),this.adLayer.on("ad_error",function(t){var i="Ad playback failed";if(t){var r=t.code||t.errorCode||"unknown",n=t.vastErrorCode,a=t.message||t.errorMessage||"Unknown error",s=t.cause||t.innerError||t.error;if(i="Ad error: AdError ".concat(r,": ").concat(a),n&&"N/A"!==n&&n!==r&&(i+=" (VAST Error Code: ".concat(n,")")),s){var o="string"==typeof s?s:s.message||String(s);i+=". Caused by: ".concat(o)}}console.error("[AD-ERROR]",i,t||""),e.adLayer.stop().catch(function(){}),e.handleAdFailure()}),this.adLayer.on("content_pause",function(){e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!0,e.inAdBreak&&null!=e.expectedAdBreakDurationMs&&null==e.adStopTimerId&&(e.scheduleAdStopCountdown(e.getRemainingAdMs()),e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)")),e.adLayer.setAdVolume(e.adLayer.getOriginalMutedState()?1:e.adLayer.getOriginalVolume()),e.stopFillerBreakTimer(),e.hidePlaceholderLayer(),e.isShowingPlaceholder=!1,e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Hiding placeholder - new ads starting")}),this.adLayer.on("content_resume",function(){var t=e.getRemainingAdMs();if(e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] content_resume received, inAdBreak=%s, remaining=%s, pendingNext=%s",e.inAdBreak,t,!!e.pendingNextAdBids),e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!1,!e.inAdBreak)return e.video.style.visibility="visible",e.video.style.opacity="1",void e.syncMainContentAudioWhenVisible();if(e.consecutiveFailures=0,e.pendingNextAdBids&&e.pendingNextAdBids.length>0){var i=M([],x(e.pendingNextAdBids),!1);return e.pendingNextAdBids=null,e.video.muted||(e.video.muted=!0,e.video.volume=0),e.showPlaceholderLayer(),e.adLayer.showPlaceholder(),e.isInAdTransition=!0,void setTimeout(function(){var t;if(e.isInAdTransition=!1,e.inAdBreak&&0!==i.length){var r=null!==(t=e.pendingNextAdBids)&&void 0!==t?t:i;e.pendingNextAdBids=null,e.currentAdIndex++,e.adLayer.playAd(r).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] playAd(pending) failed:",t),e.handleAdFailure()})}},e.adTransitionGapMs)}e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] content_resume: no more ads, ending ad pod and restoring main content sound"),e.handleAdPodComplete()})},e.prototype.ensureFillerVideo=function(){if(!this.fillerVideo&&this.video.parentElement){var e=document.createElement("video");e.src="https://f000.backblazeb2.com/file/AdStormAds/384/Sonifi_Filler.mp4",e.loop=!0,e.muted=!1,e.playsInline=!0,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="cover",e.style.zIndex="20",e.style.display="none",e.preload="auto",this.video.parentElement.appendChild(e),this.fillerVideo=e}},e.prototype.showPlaceholderLayer=function(){var e=this;this.ensureFillerVideo(),this.fillerVideo&&(this.video.muted||(this.video.muted=!0,this.video.volume=0),this.fillerVideo.style.display="block",this.fillerVideo.play().catch(function(){e.fillerVideo&&(e.fillerVideo.style.display="none")}),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Showing filler video layer"))},e.prototype.hidePlaceholderLayer=function(){this.fillerVideo&&(this.fillerVideo.style.display="none",this.fillerVideo.pause(),this.fillerVideo.currentTime=0,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Hiding filler video layer"))},e.prototype.startFillerBreakTimer=function(e){var t=this;this.stopFillerBreakTimer(),this.showPlaceholderLayer(),this.fillerBreakTimerId=setTimeout(function(){t.fillerBreakTimerId=void 0,t.hidePlaceholderLayer(),t.inAdBreak&&t.handleAdPodComplete()},e)},e.prototype.stopFillerBreakTimer=function(){void 0!==this.fillerBreakTimerId&&(clearTimeout(this.fillerBreakTimerId),this.fillerBreakTimerId=void 0)},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.adLayer.initialize(),this.ensureFillerVideo(),this.adLayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.attachAdLayerEventListeners(),this.timeUpdateHandler=function(){e.onTimeUpdate(e.video.currentTime)},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.nativeHlsMode&&e.videoSrcProtection&&!e.adLayer.isAdPlaying()){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",e.videoSrcProtection);var t=e.video.currentTime,i=e.video.paused;e.video.src=e.videoSrcProtection,e.video.currentTime=t,i||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,i,r,n,a=this.decodeId3ValueToText(e.value);if(a){var s=a.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||a.match(/CUE-OUT(?::([^\r\n]*))?/i);if(s){var o=(null!==(t=s[1])&&void 0!==t?t:"").trim(),l=this.parseCueOutDuration(o);return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==l?{durationSeconds:l}:{}),{raw:{id3:a}})}var u=a.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(u){o=(null!==(i=u[1])&&void 0!==i?i:"").trim();var c=this.parseCueOutCont(o);return w(w(w({type:"progress"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==(null==c?void 0:c.duration)?{durationSeconds:c.duration}:{}),{raw:{id3:a}})}if(a.match(/EXT-X-CUE-IN\b/i)||a.match(/CUE-IN\b/i))return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});var d=a.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(d){var h=this.parseAttributeList(null!==(r=d[1])&&void 0!==r?r:""),f="SCTE35-OUT"in h||void 0!==h["SCTE35-OUT"],v="SCTE35-IN"in h||void 0!==h["SCTE35-IN"],g=String(null!==(n=h.CLASS)&&void 0!==n?n:""),m=this.toNumber(h.DURATION);if(f||/com\.apple\.hls\.cue/i.test(g))return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==m?{durationSeconds:m}:{}),{raw:{id3:a,attrs:h}});if(v)return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a,attrs:h}})}if(/SCTE35-OUT/i.test(a))return w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(/SCTE35-IN/i.test(a))return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(e.value instanceof Uint8Array){var p=this.parseScte35Binary(e.value);if(p)return p}}},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 i="",r=0;r<e.length;r++)i+=String.fromCharCode(e[r]);return i}catch(e){return}},e.prototype.onScte35Marker=function(e){var t,i,r,n,a=this;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime,raw:e.raw,hasPendingAdBreak:!!this.pendingAdBreak}),"start"!==e.type){if("progress"===e.type&&this.inAdBreak){if(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs){var s=Date.now()-this.currentAdBreakStartWallClockMs,o=Math.max(0,this.expectedAdBreakDurationMs-s);this.scheduleAdStopCountdown(o)}if(!this.adLayer.isAdPlaying()&&null!=this.pendingNextAdBids&&this.pendingNextAdBids.length>0){var l=this.pendingNextAdBids;this.pendingNextAdBids=null,this.currentAdIndex++,this.adLayer.playAd(l).catch(function(){return a.handleAdFailure()})}}else if("end"===e.type){var u=this.getRemainingAdMs(),c=this.adLayer.isAdPlaying(),d=null!=this.pendingNextAdBids&&this.pendingNextAdBids.length>0;return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 end marker received:",{inAdBreak:this.inAdBreak,remaining:u,adPlaying:c,hasQueuedAds:d,activeAdRequest:null!==this.activeAdRequestToken}),this.inAdBreak?c||u>500?void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ignoring premature SCTE-35 end marker - ads still active or time remaining")):(this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),c&&this.adLayer.stop().catch(function(){}),void this.handleAdPodComplete()):void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ignoring SCTE-35 end marker - not in ad break"))}}else{if(null==this.savedMutedStateBeforeScte&&(this.savedMutedStateBeforeScte={muted:this.video.muted,volume:this.video.volume},this.adLayer.updateOriginalMutedState(this.video.muted,this.video.volume)),this.video.muted||(this.video.muted=!0,this.video.volume=0,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted video on SCTE start marker")),this.inAdBreak)return void(null==this.expectedAdBreakDurationMs&&null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Updated ad break duration from subsequent marker: ".concat(this.expectedAdBreakDurationMs,"ms")),this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)));this.inAdBreak=!0;var h=null!=e.durationSeconds?1e3*e.durationSeconds:null!=(null===(t=this.pendingAdBreak)||void 0===t?void 0:t.marker.durationSeconds)?1e3*this.pendingAdBreak.marker.durationSeconds:void 0;if(this.expectedAdBreakDurationMs=h,this.currentAdBreakStartWallClockMs=Date.now(),this.config.licenseKey){var f=w(w(w({source:"scte35",timestamp:(new Date).toISOString()},null!=e.durationSeconds&&{durationSeconds:e.durationSeconds}),null!=e.ptsSeconds&&{ptsSeconds:e.ptsSeconds}),null!=(null===(i=this.pendingAdBreak)||void 0===i?void 0:i.detectedAtFragmentSn)&&{detectedAtFragmentSn:this.pendingAdBreak.detectedAtFragmentSn});!function(e,t){D(this,void 0,void 0,function(){var i,r,n,a;return C(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,wu(i=Ru())];case 1:return r=s.sent(),n=w({browserId:r},i),[4,Du(e,w(w({},n),{licenseKey:e,adDetectInfo:t}))];case 2:return s.sent(),[3,4];case 3:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending ad detect tracking:",a),[3,4];case 4:return[2]}})})}(this.config.licenseKey,f)}var v=this.isManifestBasedMarker(e),g=null===(r=this.config.immediateManifestAds)||void 0===r||r;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:v,forceImmediate:g,hasPts:"number"==typeof e.ptsSeconds}),v&&g)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)"),this.clearAdStartTimer(),this.handleAdStart(e);else if("number"==typeof e.ptsSeconds){var m=null!==(n=this.config.driftToleranceMs)&&void 0!==n?n:1e3,p=1e3*this.video.currentTime,y=p-this.ptsDriftEmaMs,E=Math.floor(1e3*e.ptsSeconds-y);this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:p,estCurrentPtsMs:y,markerPtsMs:1e3*e.ptsSeconds,deltaMs:E,tolerance:m}),E>m?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Scheduling ad start in ".concat(E,"ms")),this.scheduleAdStartIn(E)):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.clearAdStartTimer(),this.handleAdStart(e))}else this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.clearAdStartTimer(),this.handleAdStart(e);null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)}},e.prototype.parseCueOutDuration=function(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var i=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(i&&null!=i[1]){var r=i[1],n=parseFloat(r);return Number.isNaN(n)?void 0:n}},e.prototype.parseCueOutCont=function(e){var t={},i=e.match(/Elapsed\s*=\s*([0-9.]+)/i),r=e.match(/Duration\s*=\s*([0-9.]+)/i);if(i&&null!=i[1]){var n=parseFloat(i[1]);Number.isNaN(n)||(t.elapsed=n)}if(r&&null!=r[1]){var a=parseFloat(r[1]);Number.isNaN(a)||(t.duration=a)}if(!("elapsed"in t)||!("duration"in t)){var s=e.match(/([0-9.]+)\s*\/\s*([0-9.]+)/);if(s&&s[1]&&s[2]){var o=parseFloat(s[1]),l=parseFloat(s[2]);Number.isNaN(o)||"elapsed"in t||(t.elapsed=o),Number.isNaN(l)||"duration"in t||(t.duration=l)}}if("elapsed"in t||"duration"in t)return t},e.prototype.parseAttributeList=function(e){for(var t,i,r,n,a={},s=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(n=s.exec(e));){var o=null!==(t=n[1])&&void 0!==t?t:"",l=null!==(r=null!==(i=n[3])&&void 0!==i?i:n[4])&&void 0!==r?r:"";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.isManifestBasedMarker=function(e){var t=e.raw;if(!t)return!1;if(t.tag){var i=String(t.tag);return i.includes("EXT-X-CUE-OUT")||i.includes("EXT-X-CUE-IN")||i.includes("EXT-X-DATERANGE")}return t.id3||t.splice_command_type,!1},e.prototype.parseScte35Binary=function(e){var t=new(function(){function e(e){this.buf=e,this.bytePos=0,this.bitPos=0}return e.prototype.readBits=function(e){for(var t=0;e>0;){if(this.bytePos>=this.buf.length)return t;var i=8-this.bitPos,r=Math.min(e,i);t=t<<r|this.buf[this.bytePos]>>i-r&((1<<r)-1&255),this.bitPos+=r,this.bitPos>=8&&(this.bitPos=0,this.bytePos+=1),e-=r}return t>>>0},e.prototype.skipBits=function(e){this.readBits(e)},e}())(e);if(252===t.readBits(8)){t.readBits(1),t.readBits(1),t.readBits(2);t.readBits(12);t.readBits(8),t.readBits(1),t.readBits(6);t.readBits(1),t.readBits(32);t.readBits(8),t.readBits(12);t.readBits(12);if(5===t.readBits(8)){t.readBits(32);var i=1===t.readBits(1);if(t.readBits(7),!i){var r=1===t.readBits(1),n=1===t.readBits(1),a=1===t.readBits(1),s=1===t.readBits(1);if(t.readBits(4),n&&!s)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7);else if(!n)for(var o=t.readBits(8),l=0;l<o;l++){if(t.readBits(8),!s)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}var u=void 0;if(a)t.readBits(6),t.readBits(1),u=(4294967296*t.readBits(1)+t.readBits(32))/9e4;if(t.readBits(16),t.readBits(8),t.readBits(8),r)return w(w({type:"start"},void 0!==u?{durationSeconds:u}:{}),{raw:{splice_command_type:5}})}}}},e.prototype.initializeTracking=function(){var e=this;Cu(this.config.licenseKey).then(function(){e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)}).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send initial tracking:",t),e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)})},e.prototype.sendHeartbeatIfNeeded=function(){var e=this,t=Date.now();(!this.lastHeartbeatTime||t-this.lastHeartbeatTime>3e4)&&(this.lastHeartbeatTime=t,xu(this.config.licenseKey).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",t)}))},e.prototype.getCurrentAdIndex=function(){return this.currentAdIndex},e.prototype.getTotalAdsInBreak=function(){return this.totalAdsInBreak},e.prototype.isAdPlaying=function(){return this.inAdBreak&&this.adLayer.isAdPlaying()},e.prototype.isShowingAds=function(){return this.showAds},e.prototype.syncMainContentAudioWhenVisible=function(){if(!(this.showAds||this.adLayer.isAdPlaying())){var e=this.adLayer.getOriginalMutedState(),t=this.adLayer.getOriginalVolume();this.video.muted!==e&&(this.video.muted=e),Math.abs(this.video.volume-t)>.01&&(this.video.volume=t)}},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.shouldContinueLiveStreamDuringAds=function(){return!this.config.allowNativeHls&&!!this.isLiveStream},e.prototype.startAdPrefetch=function(e,t){var i=this;this.pendingAdBreak||this.inAdBreak||(this.pendingAdBreak=w(w({marker:e},void 0!==t?{detectedAtFragmentSn:t}:{}),{isFetching:!1,fetchStartTime:Date.now()}),this.adRequest().then(function(){}).catch(function(){i.config.debugAdTiming&&console.log("[PREFETCH] Prebid auction prefetch failed, will request at playback time")}),this.config.debugAdTiming&&console.log("[PREFETCH] Ad break marker registered, auction prefetch started"))},e.prototype.clearPendingAdBreak=function(){null!=this.prefetchTimerId&&(clearTimeout(this.prefetchTimerId),this.prefetchTimerId=void 0),this.pendingAdBreak=null},e.prototype.startContinuousFetchLoop=function(){null==this.continuousFetchLoopPromise&&(this.continuousFetchLoopPromise=this.runContinuousFetchLoop())},e.prototype.runContinuousFetchLoop=function(){return D(this,void 0,void 0,function(){var e,t,i,r=this;return C(this,function(n){switch(n.label){case 0:e=function(){var e=Math.pow(2,r.consecutiveFailures);return Math.min(r.backoffBaseMs*e,r.maxBackoffMs)},t=function(){var t,r,n,a;return C(this,function(s){switch(s.label){case 0:return i.consecutiveFailures>=i.maxConsecutiveFailures||i.totalAdRequestsInBreak>=i.maxTotalAdRequestsPerBreak?[2,"break"]:(t=i.lastAdRequestTime?i.minAdRequestIntervalMs+(i.consecutiveFailures>0?e():0):0,(r=Date.now()-i.lastAdRequestTime)<t&&i.lastAdRequestTime>0?[4,new Promise(function(e){return setTimeout(e,t-r)})]:[3,2]);case 1:s.sent(),s.label=2;case 2:if(!i.inAdBreak||!i.continuousFetchingActive)return[2,"break"];s.label=3;case 3:return s.trys.push([3,10,,11]),[4,i.adRequest()];case 4:return n=s.sent(),i.lastAdRequestTime=Date.now(),i.inAdBreak?n.length>0?(i.consecutiveFailures=0,i.adLayer.isAdPlaying()||i.isInAdTransition?(i.pendingNextAdBids=n,i.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] Next ad response stored (ad currently playing or in transition)"),[3,7]):[3,5]):[3,8]:[2,"break"];case 5:return i.currentAdIndex++,i.config.licenseKey&&_u(i.config.licenseKey,{source:i.getAdSource(),timestamp:(new Date).toISOString()}),[4,i.adLayer.playAd(n)];case 6:s.sent(),null!=i.expectedAdBreakDurationMs&&null==i.adStopTimerId&&i.scheduleAdStopCountdown(i.getRemainingAdMs()),i.adLayer.setAdVolume(i.adLayer.getOriginalMutedState()?1:i.adLayer.getOriginalVolume()),s.label=7;case 7:return[3,9];case 8:i.consecutiveFailures++,s.label=9;case 9:return[3,11];case 10:return a=s.sent(),i.consecutiveFailures++,i.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] adRequest failed:",a),[3,11];case 11:return[4,new Promise(function(t){return setTimeout(t,e())})];case 12:return s.sent(),[2]}})},i=this,n.label=1;case 1:return this.inAdBreak&&this.continuousFetchingActive?[5,t()]:[3,3];case 2:return"break"===n.sent()?[3,3]:[3,1];case 3:return this.continuousFetchLoopPromise=null,[2]}})})},e.prototype.handleAdStart=function(e){return D(this,void 0,void 0,function(){var t,i,r,n,a,s,o,l;return C(this,function(u){switch(u.label){case 0:t=null!=e.durationSeconds?1e3*e.durationSeconds:void 0,this.config.debugAdTiming&&(i=this.isLiveStream?"LIVE":"VOD",console.log("[CONTINUOUS-FETCH] 📺 ".concat(i," MODE: Target duration=").concat(t,"ms"))),this.consecutiveFailures=0,this.continuousFetchingActive=!0,this.continuousFetchLoopPromise=null,this.pendingNextAdBids=null,this.isShowingPlaceholder=!1,this.totalAdRequestsInBreak=0,null!=this.savedMutedStateBeforeScte||this.video.muted||(this.savedMutedStateBeforeScte={muted:!1,volume:this.video.volume}),r=null!==(l=this.savedMutedStateBeforeScte)&&void 0!==l?l:{muted:this.video.muted,volume:this.video.volume},this.adLayer.updateOriginalMutedState(r.muted,r.volume),this.video.muted||(this.video.muted=!0,this.video.volume=0,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted video in handleAdStart")),this.inAdBreak=!0,this.currentAdBreakStartWallClockMs=Date.now(),this.currentAdIndex=0,this.totalAdsInBreak=1,this.adPodQueue=[],this.showAds=!0,null!=t?this.startFillerBreakTimer(t):this.showPlaceholderLayer(),this.adLayer.showPlaceholder(),null==this.expectedAdBreakDurationMs&&null!=t&&(this.expectedAdBreakDurationMs=t),this.clearPendingAdBreak(),n=Date.now(),this.activeAdRequestToken=n,this.startAdFailsafeTimer(n),this.startAdRequestWatchdog(n),u.label=1;case 1:return u.trys.push([1,7,,9]),this.lastAdRequestTime=Date.now(),[4,this.adRequest()];case 2:return a=u.sent(),this.inAdBreak?a.length>0?(this.consecutiveFailures=0,this.config.licenseKey&&_u(this.config.licenseKey,{source:this.getAdSource(),timestamp:(new Date).toISOString()}),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ First ad request successful, starting playback"),this.currentAdIndex++,[4,this.adLayer.playAd(a)]):[3,4]:[2];case 3:return u.sent(),null!=this.expectedAdBreakDurationMs&&null==this.adStopTimerId&&this.scheduleAdStopCountdown(this.getRemainingAdMs()),s=r.muted?1:r.volume,this.adLayer.setAdVolume(s),[3,6];case 4:return this.consecutiveFailures++,[4,this.showPlaceholderAndWaitForAds()];case 5:u.sent(),u.label=6;case 6:return[3,9];case 7:return o=u.sent(),this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ First ad request failed:",o),this.consecutiveFailures++,[4,this.showPlaceholderAndWaitForAds()];case 8:return u.sent(),[3,9];case 9:return this.startContinuousFetchLoop(),[2]}})})},e.prototype.stopContinuousFetching=function(){this.continuousFetchingActive=!1,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching")},e.prototype.tryNextAvailableAdWithRateLimit=function(){return D(this,void 0,void 0,function(){var e,t,i,r,n;return C(this,function(a){switch(a.label){case 0:return this.consecutiveFailures>=this.maxConsecutiveFailures?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (".concat(this.consecutiveFailures,"), ending ad break gracefully")),this.handleAdPodComplete(),[2]):(e=Math.pow(2,this.consecutiveFailures),t=Math.min(this.backoffBaseMs*e,this.maxBackoffMs),i=this.minAdRequestIntervalMs+(this.consecutiveFailures>0?t:0),(r=Date.now()-this.lastAdRequestTime)<i?(n=i-r,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏳ Rate limiting: waiting ".concat(n,"ms before next request (backoff: ").concat(this.consecutiveFailures," failures)")),[4,new Promise(function(e){return setTimeout(e,n)})]):[3,2]);case 1:a.sent(),a.label=2;case 2:return[2,this.tryNextAvailableAd(0)]}})})},e.prototype.tryNextAvailableAd=function(){return D(this,arguments,void 0,function(e){var t,i;return void 0===e&&(e=0),C(this,function(e){switch(e.label){case 0:if(this.totalAdRequestsInBreak>=this.maxTotalAdRequestsPerBreak)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Max ad requests per break (".concat(this.maxTotalAdRequestsPerBreak,") reached")),this.handleAdPodComplete(),[2];if(this.getRemainingAdMs()<=500&&null!=this.expectedAdBreakDurationMs)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break"),this.handleAdPodComplete(),[2];if(this.consecutiveFailures>=this.maxConsecutiveFailures)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Too many consecutive failures (".concat(this.consecutiveFailures,"), ending ad break")),this.handleAdPodComplete(),[2];e.label=1;case 1:return e.trys.push([1,9,,11]),this.lastAdRequestTime=Date.now(),[4,this.adRequest()];case 2:return t=e.sent(),this.inAdBreak?t.length>0?(this.consecutiveFailures=0,this.currentAdIndex++,this.totalAdRequestsInBreak++,this.adLayer.isAdPlaying()||this.isInAdTransition?(this.pendingNextAdBids=t,[3,5]):[3,3]):[3,6]:[2];case 3:return this.config.licenseKey&&_u(this.config.licenseKey,{source:this.getAdSource(),timestamp:(new Date).toISOString()}),[4,this.adLayer.playAd(t)];case 4:e.sent(),null!=this.expectedAdBreakDurationMs&&null==this.adStopTimerId&&this.scheduleAdStopCountdown(this.getRemainingAdMs()),this.adLayer.setAdVolume(this.adLayer.getOriginalMutedState()?1:this.adLayer.getOriginalVolume()),e.label=5;case 5:return[3,8];case 6:return this.consecutiveFailures++,[4,this.showPlaceholderAndWaitForAds()];case 7:e.sent(),e.label=8;case 8:return[3,11];case 9:return i=e.sent(),this.consecutiveFailures++,this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] tryNextAvailableAd request failed:",i),[4,this.showPlaceholderAndWaitForAds()];case 10:return e.sent(),[3,11];case 11:return[2]}})})},e.prototype.showPlaceholderAndWaitForAds=function(){return D(this,void 0,void 0,function(){var e,t,i,r,n,a,s;return C(this,function(o){switch(o.label){case 0:if(e=this.getRemainingAdMs(),t=Math.min(this.maxPlaceholderDurationMs,e),this.consecutiveFailures>=this.maxConsecutiveFailures)return this.getRemainingAdMs()>=1e3?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Max failures reached but break still active — resetting and continuing filler"),this.consecutiveFailures=0,[2]):(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Skipping placeholder - too many consecutive failures"),this.handleAdPodComplete(),[2]);if(t<1e3)return this.handleAdPodComplete(),[2];this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⬛ Showing placeholder for ".concat(t,"ms while waiting for ad response")),this.isShowingPlaceholder=!0,this.showPlaceholderLayer(),this.adLayer.showPlaceholder(),i=300,r=Math.floor(t/i),n=0,o.label=1;case 1:return n<r?[4,new Promise(function(e){return setTimeout(e,i)})]:[3,10];case 2:if(o.sent(),!this.inAdBreak)return[2];if(this.consecutiveFailures>=this.maxConsecutiveFailures)return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Too many failures during placeholder wait — resetting and continuing filler"),this.consecutiveFailures=0,[3,10];if(!(null!=this.pendingNextAdBids&&this.pendingNextAdBids.length>0))return[3,8];a=this.pendingNextAdBids,this.pendingNextAdBids=null,this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),this.currentAdIndex++,o.label=3;case 3:return o.trys.push([3,5,,7]),[4,this.adLayer.playAd(a)];case 4:return o.sent(),this.consecutiveFailures=0,[3,7];case 5:return o.sent(),this.consecutiveFailures++,[4,this.tryNextAvailableAdWithRateLimit()];case 6:return o.sent(),[3,7];case 7:return[2];case 8:if(this.adLayer.isAdPlaying())return this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),[2];o.label=9;case 9:return n++,[3,1];case 10:return(s=this.getRemainingAdMs())>=1e3?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder slot expired, ".concat(s,"ms still remaining — continuing filler")),this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),this.consecutiveFailures=0,[2]):(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder timeout, ending ad break"),this.isShowingPlaceholder=!1,this.adLayer.hidePlaceholder(),this.handleAdPodComplete(),[2])}})})},e.prototype.onTimeUpdate=function(e){this.adLayer.isAdPlaying()},e.prototype.scheduleAdStopCountdown=function(e){var t=this;this.clearAdStopTimer();var i=Math.max(0,Math.floor(e));0!==i?this.adStopTimerId=window.setTimeout(function(){t.ensureAdStoppedByTimer()},i):this.ensureAdStoppedByTimer()},e.prototype.clearAdStopTimer=function(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)},e.prototype.ensureAdStoppedByTimer=function(){var e,t;if(this.inAdBreak){this.adStopTimerId=void 0;var i=this.adLayer.isAdPlaying(),r=this.adPodQueue.length>0,n=Math.max(250,Math.floor(null!==(e=this.config.adBreakCheckIntervalMs)&&void 0!==e?e:1e3)),a=this.config.maxAdBreakExtensionMs,s="number"==typeof a&&a>0?a:6e4,o=0;null!=this.currentAdBreakStartWallClockMs&&(o=Date.now()-this.currentAdBreakStartWallClockMs);var l=null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:0,u=Math.max(0,o-l);(i||r||this.showAds)&&u<s?this.scheduleAdStopCountdown(n):(i&&this.adLayer.stop().catch(function(){}),this.handleAdPodComplete())}},e.prototype.scheduleAdStartIn=function(e){var t=this;this.clearAdStartTimer();var i=Math.max(0,Math.floor(e));0!==i?this.adStartTimerId=window.setTimeout(function(){t.handleAdStart({type:"start"}).catch(function(){})},i):this.handleAdStart({type:"start"}).catch(function(){})},e.prototype.clearAdStartTimer=function(){null!=this.adStartTimerId&&(clearTimeout(this.adStartTimerId),this.adStartTimerId=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,t,i,r,n,a,s=this;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] 🏁 Ad pod complete - cleaning up"),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.isInAdTransition=!1,this.stopContinuousFetching(),this.stopFillerBreakTimer(),this.hidePlaceholderLayer(),this.clearPendingAdBreak(),this.pendingNextAdBids=null,this.isShowingPlaceholder&&(this.adLayer.hidePlaceholder(),this.isShowingPlaceholder=!1),this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.adPodQueue=[],this.showAds=!1,this.currentAdIndex=0,this.totalAdsInBreak=0,this.totalAdRequestsInBreak=0,this.consecutiveFailures=0;var o=null!==(t=null===(e=this.savedMutedStateBeforeScte)||void 0===e?void 0:e.muted)&&void 0!==t?t:this.adLayer.getOriginalMutedState(),l=null!==(r=null===(i=this.savedMutedStateBeforeScte)||void 0===i?void 0:i.volume)&&void 0!==r?r:this.adLayer.getOriginalVolume();this.adLayer.updateOriginalMutedState(o,l),this.adLayer.stop().catch(function(){}),this.video.muted!==o&&(this.video.muted=o),Math.abs(this.video.volume-l)>.01&&(this.video.volume=l);var u=Ou(),c=void 0!==u.tizenVersion||void 0!==u.webOSVersion;if(c&&this.hls){if(!o){var d=this.hls,h=o,f=l,v=function(){d.off(pu.Events.MANIFEST_PARSED,v),s.inAdBreak||s.adLayer.isAdPlaying()||(s.video.muted!==h&&(s.video.muted=h),Math.abs(s.video.volume-f)>.01&&(s.video.volume=f),s.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Smart TV: audio state restored on MANIFEST_PARSED after re-attach"))};d.on(pu.Events.MANIFEST_PARSED,v)}this.hls.attachMedia(this.video),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Smart TV: re-attached HLS to video element after ad break to restore media pipeline")}this.shouldContinueLiveStreamDuringAds()?(this.config.debugAdTiming&&(this.video.paused?console.log("[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback"):console.log("[StormcloudVideoPlayer] Content video already playing in live mode after ads")),null===(n=this.video.play())||void 0===n||n.catch(function(){})):this.video.paused&&(null===(a=this.video.play())||void 0===a||a.catch(function(){})),this.syncMainContentAudioWhenVisible(),o||(requestAnimationFrame(function(){s.syncMainContentAudioWhenVisible()}),setTimeout(function(){s.syncMainContentAudioWhenVisible()},0),setTimeout(function(){s.syncMainContentAudioWhenVisible()},50),setTimeout(function(){s.syncMainContentAudioWhenVisible()},100),setTimeout(function(){s.syncMainContentAudioWhenVisible()},150)),c&&!o&&[500,1e3,2e3,3e3,5e3].forEach(function(e){setTimeout(function(){s.inAdBreak||s.adLayer.isAdPlaying()||(s.video.muted!==o&&(s.video.muted=o),Math.abs(s.video.volume-l)>.01&&(s.video.volume=l))},e)}),this.savedMutedStateBeforeScte=null},e.prototype.handleAdFailure=function(){this.consecutiveFailures++,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] Ad failure: consecutiveFailures=".concat(this.consecutiveFailures)),this.consecutiveFailures>=this.maxConsecutiveFailures&&(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Max consecutive failures reached (".concat(this.consecutiveFailures,"), ending ad break gracefully")),this.handleAdPodComplete())},e.prototype.startAdRequestWatchdog=function(e){var t,i=this;this.clearAdRequestWatchdog();var r=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adRequestWatchdogToken=e,this.adRequestWatchdogId=window.setTimeout(function(){i.adRequestWatchdogToken===e&&(i.adRequestWatchdogId=void 0,i.adRequestWatchdogToken=null,i.activeAdRequestToken===e&&(i.activeAdRequestToken=null),i.logAdState("ad_request_timeout",{token:e,timeoutMs:r}),i.handleAdFailure())},r),this.logAdState("ad_request_watchdog_started",{token:e,timeoutMs:r})},e.prototype.clearAdRequestWatchdog=function(){null!=this.adRequestWatchdogId&&(clearTimeout(this.adRequestWatchdogId),this.adRequestWatchdogId=void 0),null!=this.adRequestWatchdogToken&&(this.logAdState("ad_request_watchdog_cleared",{token:this.adRequestWatchdogToken}),this.adRequestWatchdogToken=null)},e.prototype.startAdFailsafeTimer=function(e){var t,i=this;this.clearAdFailsafeTimer();var r=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adFailsafeToken=e,this.adFailsafeTimerId=window.setTimeout(function(){i.adFailsafeToken===e&&(i.adFailsafeTimerId=void 0,i.adFailsafeToken=null,i.activeAdRequestToken===e&&(i.activeAdRequestToken=null),i.logAdState("ad_failsafe_triggered",{token:e,failsafeMs:r,videoPaused:i.video.paused,imaAdPlaying:i.adLayer.isAdPlaying()}),i.handleAdFailure())},r),this.logAdState("ad_failsafe_started",{token:e,failsafeMs:r})},e.prototype.clearAdFailsafeTimer=function(){null!=this.adFailsafeTimerId&&(clearTimeout(this.adFailsafeTimerId),this.logAdState("ad_failsafe_cleared",{token:this.adFailsafeToken}),this.adFailsafeTimerId=void 0),this.adFailsafeToken=null},e.prototype.logAdState=function(e,t){void 0===t&&(t={}),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer][AdState]",w({event:e,timestamp:(new Date).toISOString(),showAds:this.showAds,adPlaying:this.adLayer.isAdPlaying(),inAdBreak:this.inAdBreak,activeAdRequestToken:this.activeAdRequestToken},t))},e.prototype.getRemainingAdMs=function(){if(null==this.currentAdBreakStartWallClockMs)return 0;if(null==this.expectedAdBreakDurationMs)return Number.MAX_SAFE_INTEGER;var e=Date.now()-this.currentAdBreakStartWallClockMs;return Math.max(0,this.expectedAdBreakDurationMs-e)},e.prototype.toggleMute=function(){if(this.adLayer.isAdPlaying()){var e=0===this.adLayer.getAdVolume();if(e){var t=this.adLayer.getOriginalVolume()||1;this.adLayer.setAdVolume(t),this.adLayer.updateOriginalMutedState(!1,t)}else{var i=this.adLayer.getAdVolume();this.adLayer.setAdVolume(0),this.adLayer.updateOriginalMutedState(!0,i)}this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Mute toggle during ad:",e?"unmuted":"muted")}else this.video.muted=!this.video.muted,this.adLayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted:",this.video.muted)},e.prototype.toggleFullscreen=function(){var e=this;return new Promise(function(t,i){if(document.fullscreenElement)document.exitFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",t),i(t)});else{var r=e.video.parentElement;if(!r)return void i(new Error("No parent container found for fullscreen"));r.requestFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Fullscreen error:",t),i(t)})}})},e.prototype.isMuted=function(){if(this.adLayer.isAdPlaying()){var e=0===this.adLayer.getAdVolume();return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] isMuted() during ad playback ->",e),e}return this.video.muted},e.prototype.setMuted=function(e){if(this.adLayer.isAdPlaying()){var t=this.adLayer.getOriginalVolume()||1;return this.adLayer.setAdVolume(e?0:t),this.adLayer.updateOriginalMutedState(e,t),void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted applied to ad layer (content stays muted)",{muted:e,savedVolume:t}))}this.video.muted=e,this.inAdBreak||this.adLayer.updateOriginalMutedState(e,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted called:",e)},e.prototype.setVolume=function(e){var t=Math.max(0,Math.min(1,e));if(this.adLayer.isAdPlaying()){this.adLayer.setAdVolume(t);var i=t>0?t:this.adLayer.getOriginalVolume();this.adLayer.updateOriginalMutedState(0===t,i),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:t})}else this.video.volume=t,this.video.muted=0===t,this.inAdBreak||this.adLayer.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume called:",t)},e.prototype.getVolume=function(){return this.adLayer.isAdPlaying()?this.adLayer.getAdVolume():this.video.volume},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.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing player"),this.adLayer&&this.adLayer.isAdPlaying()){var e=this.video.clientWidth||640,t=this.video.clientHeight||480;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing ads manager to ".concat(e,"x").concat(t)),this.adLayer.resize(e,t)}},e.prototype.destroy=function(){var e,t;this.stopContinuousFetching(),this.stopFillerBreakTimer(),this.clearAdStartTimer(),this.clearAdStopTimer(),this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.clearPendingAdBreak(),this.fillerVideo&&(this.fillerVideo.pause(),this.fillerVideo.parentElement&&this.fillerVideo.parentElement.removeChild(this.fillerVideo),this.fillerVideo=void 0),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.adLayer)||void 0===t||t.destroy(),this.consecutiveFailures=0},e}(),Gu={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Vu=z.createContext&&z.createContext(Gu),Hu=["attr","size","title"];function Ku(e,t){if(null==e)return{};var i,r,n=function(e,t){if(null==e)return{};var i={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;i[r]=e[r]}return i}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)i=a[r],t.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}function ju(){return ju=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},ju.apply(this,arguments)}function Wu(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function qu(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Wu(Object(i),!0).forEach(function(t){Yu(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Wu(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Yu(e,t,i){var r;return r=function(e,t){if("object"!=S(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=S(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==S(r)?r:r+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function zu(e){return e&&e.map(function(e,t){return z.createElement(e.tag,qu({key:t},e.attr),zu(e.child))})}function Xu(e){return function(t){return z.createElement(Qu,ju({attr:qu({},e.attr)},t),zu(e.child))}}function Qu(e){var t=function(t){var i,r=e.attr,n=e.size,a=e.title,s=Ku(e,Hu),o=n||t.size||"1em";return t.className&&(i=t.className),e.className&&(i=(i?i+" ":"")+e.className),z.createElement("svg",ju({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,r,s,{className:i,style:qu(qu({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!==Vu?z.createElement(Vu.Consumer,null,function(e){return t(e)}):t(Gu)}function $u(e){return Xu({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 Ju(e){return Xu({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 Zu(e){return Xu({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 ec(e){return Xu({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 tc(e){return Xu({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 ic(e){return Xu({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 rc(e){return Xu({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 nc(e){return Xu({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 ac=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs"],sc=z.memo(function(e){var t=e.src,i=e.autoplay,r=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,m=e.wrapperStyle,p=e.className,y=e.style,E=e.controls,T=e.playsInline,k=e.preload,S=e.poster,A=e.children,b=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=Y.useRef(null),D=Y.useRef(null),C=Y.useRef(null),_=Y.useRef(null),M=Y.useRef(null),O=x(z.useState({showAds:!1,currentIndex:0,totalAds:0}),2),F=O[0],N=O[1],B=x(z.useState(!0),2),U=B[0],G=B[1],V=x(z.useState(!1),2),H=V[0],K=V[1],j=x(z.useState(!1),2),W=j[0],X=j[1],Q=x(z.useState(!1),2),$=Q[0],J=Q[1],Z=x(z.useState(0),2),ee=Z[0],te=Z[1],ie=x(z.useState(0),2),re=ie[0],ne=ie[1],ae=x(z.useState(1),2),se=ae[0],oe=ae[1],le=x(z.useState(1),2),ue=le[0],ce=le[1],de=x(z.useState(!1),2),he=de[0],fe=de[1],ve=x(z.useState(!1),2),ge=ve[0],me=ve[1],pe=x(z.useState(!0),2),ye=pe[0],Ee=pe[1],Te=x(z.useState(!1),2),ke=Te[0],Se=Te[1],Ae=x(z.useState(!1),2),be=Ae[0],Le=Ae[1],Ie=x(z.useState(!1),2),Re=Ie[0],we=Ie[1],Pe=x(z.useState(!0),2),De=Pe[0],Ce=Pe[1],_e=x(z.useState("undefined"!=typeof window?window.innerWidth:1920),2),xe=_e[0],Me=_e[1],Oe=x(z.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),Fe=Oe[0],Ne=Oe[1],Be=xe<480?.7:xe<768?.8:xe<1024?.9:1,Ue=Y.useCallback(function(){_.current&&clearTimeout(_.current),Ce(!0),_.current=window.setTimeout(function(){he||ge||Ce(!1)},3e3)},[he,ge]),Ge=function(e){if(!isFinite(e))return"0:00:00";var t=Math.floor(e/3600),i=Math.floor(e%3600/60),r=Math.floor(e%60);return"".concat(t,":").concat(i.toString().padStart(2,"0"),":").concat(r.toString().padStart(2,"0"))},Ve=function(e){if(D.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));D.current.setVolume(t)}},He=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),Ke=u&&(!He||a),je=Y.useMemo(function(){return ac.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,a,b,n,s]);Y.useEffect(function(){if("undefined"!=typeof window){var e=R.current;if(e&&t){if(!b)return we(!0),void Ee(!1);if(we(!1),D.current){try{D.current.destroy()}catch(e){}D.current=null}var c={src:t,videoElement:e};void 0!==i&&(c.autoplay=i),void 0!==r&&(c.muted=r),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!==b&&(c.licenseKey=b),void 0!==L&&(c.minSegmentsBeforePlay=L);var g=new Uu(c);return D.current=g,g.load().then(function(){var e=g.shouldShowNativeControls();G(e),null==v||v(g)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),Ee(!1),null==v||v(g)}),function(){try{g.destroy()}catch(e){}D.current=null}}}},[je]),Y.useEffect(function(){if(D.current)try{void 0!==i&&D.current.videoElement&&(D.current.videoElement.autoplay=i),void 0===r||D.current.isShowingAds()||D.current.setMuted(r)}catch(e){console.warn("Failed to update player properties:",e)}},[i,r]),Y.useEffect(function(){if(D.current){var e=setInterval(function(){var e,t;if(D.current){var i=D.current.isShowingAds(),r="true"===(null===(t=null===(e=R.current)||void 0===e?void 0:e.dataset)||void 0===t?void 0:t.stormcloudAdPlaying),n=i||r,a=D.current.getCurrentAdIndex(),s=D.current.getTotalAdsInBreak();N(function(e){return e.showAds!==n||e.currentIndex!==a||e.totalAds!==s?(n&&!e.showAds&&Le(!1),{showAds:n,currentIndex:a,totalAds:s}):e})}},50);return function(){return clearInterval(e)}}},[]),Y.useEffect(function(){if("undefined"!=typeof window&&D.current){var e=function(){D.current&&R.current&&"function"==typeof D.current.resize&&D.current.resize(),Me(window.innerWidth),Ne(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),Y.useEffect(function(){if(D.current&&R.current){var e=setInterval(function(){if(D.current&&R.current){K(D.current.isMuted()),J(!R.current.paused);var e=R.current.currentTime;te(isFinite(e)?e:0);var t=R.current.duration;ne(isFinite(t)?t:0);var i=D.current.getVolume();oe(isFinite(i)?Math.max(0,Math.min(1,i)):1);var r=R.current.playbackRate;ce(isFinite(r)&&r>0?r:1)}X(document.fullscreenElement===M.current)},200),t=function(){X(document.fullscreenElement===M.current)};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),Y.useEffect(function(){if(R.current){var e=function(){Ee(!1),C.current&&(clearTimeout(C.current),C.current=null),Se(!1)},t=function(){Ee(!1),C.current&&(clearTimeout(C.current),C.current=null),Se(!1)},i=function(){C.current&&clearTimeout(C.current),C.current=window.setTimeout(function(){Se(!0)},300)},r=function(){Ee(!1),C.current&&(clearTimeout(C.current),C.current=null),Se(!1),Le(!1)},n=function(){var e,t,i,r=(null===(e=D.current)||void 0===e?void 0:e.isShowingAds())||"true"===(null===(i=null===(t=R.current)||void 0===t?void 0:t.dataset)||void 0===i?void 0:i.stormcloudAdPlaying);D.current&&!r?Le(!0):Le(!1)},a=function(){Le(!0)},s=R.current;return s.addEventListener("canplay",e),s.addEventListener("canplaythrough",t),s.addEventListener("waiting",i),s.addEventListener("playing",r),s.addEventListener("pause",n),s.addEventListener("ended",a),s.paused&&Le(!0),function(){C.current&&(clearTimeout(C.current),C.current=null),s.removeEventListener("canplay",e),s.removeEventListener("canplaythrough",t),s.removeEventListener("waiting",i),s.removeEventListener("playing",r),s.removeEventListener("pause",n),s.removeEventListener("ended",a)}}},[l]),Y.useEffect(function(){return function(){_.current&&clearTimeout(_.current)}},[]);var We=Y.useCallback(function(){Ue()},[Ue]),qe=Y.useCallback(function(){he||ge||Ce(!1)},[he,ge]),Ye=re>0?ee/re*100:0,ze=H||0===se?rc:se<.5?ic:nc;return q.jsxs(q.Fragment,{children:[q.jsx("style",{children:"\n @keyframes sc-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes sc-pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.6; }\n }\n @keyframes sc-fade-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n .sc-wrapper:fullscreen,\n .sc-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 .sc-ctrl-btn {\n background: none;\n border: none;\n color: #fff;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n padding: 8px;\n transition: background 0.15s ease, opacity 0.15s ease;\n opacity: 0.9;\n }\n .sc-ctrl-btn:hover {\n opacity: 1;\n background: rgba(255, 255, 255, 0.1);\n }\n .sc-ctrl-btn:active {\n opacity: 0.7;\n }\n .sc-controls-bar {\n transition: opacity 0.35s ease, transform 0.35s ease;\n }\n .sc-progress-track:hover .sc-progress-thumb {\n transform: translate(-50%, -50%) scale(1) !important;\n }\n .sc-loading-hidden .sc-loading-indicator {\n display: none !important;\n }\n "}),q.jsxs("div",{ref:M,className:"sc-wrapper ".concat(g||""),onMouseMove:We,onMouseLeave:qe,style:w({display:"flex",alignItems:"center",justifyContent:"center",position:W?"fixed":"relative",top:W?0:void 0,left:W?0:void 0,overflow:"hidden",width:W?"100vw":"100%",height:W?"100vh":"auto",minHeight:W?"100vh":"auto",maxWidth:W?"100vw":"100%",maxHeight:W?"100vh":"none",zIndex:W?999999:void 0,backgroundColor:"#000",borderRadius:W?0:void 0,boxShadow:W?"none":void 0},m),children:[q.jsx("video",w({ref:R,className:p,style:w({display:"block",width:"100%",height:W?"100%":"auto",maxWidth:"100%",maxHeight:W?"100%":"none",objectFit:W?"cover":"contain",backgroundColor:"#000",aspectRatio:W?"unset":void 0},y),controls:U&&E&&!u,playsInline:T,preload:k,poster:S},I,{children:A})),(ye||ke)&&!c&&q.jsx(tc,{className:"sc-loading-indicator",size:40,color:"rgba(255, 255, 255, 0.85)",style:{position:"absolute",top:"calc(50% - 20px)",left:"calc(50% - 20px)",zIndex:20,animation:"sc-spin 0.9s linear infinite",filter:"drop-shadow(0 2px 8px rgba(0, 0, 0, 0.6))"}}),Re&&q.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"rgba(220, 38, 38, 0.92)",backdropFilter:"blur(24px)",color:"white",padding:"28px 36px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",boxShadow:"0 24px 64px rgba(0, 0, 0, 0.5)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[q.jsx("div",{style:{fontSize:"18px",fontWeight:"700",marginBottom:"10px",letterSpacing:"-0.02em"},children:"License Key Required"}),q.jsxs("div",{style:{fontSize:"13px",lineHeight:"1.6",color:"rgba(255, 255, 255, 0.85)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",q.jsx("br",{}),"Contact your administrator for licensing information."]})]}),be&&!ye&&!ke&&!Re&&!F.showAds&&q.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)}),Le(!1)))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"rgba(0, 0, 0, 0.55)",backdropFilter:"blur(20px)",WebkitBackdropFilter:"blur(20px)",borderRadius:"50%",width:"".concat(Math.max(64,80*Be),"px"),height:"".concat(Math.max(64,80*Be),"px"),display:"flex",alignItems:"center",justifyContent:"center",border:"1.5px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.5)",transition:"all 0.25s ease"},onMouseEnter:function(e){var t=e.currentTarget;t.style.background="rgba(255, 255, 255, 0.15)",t.style.borderColor="rgba(255, 255, 255, 0.35)",t.style.transform="translate(-50%, -50%) scale(1.08)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.background="rgba(0, 0, 0, 0.55)",t.style.borderColor="rgba(255, 255, 255, 0.2)",t.style.transform="translate(-50%, -50%) scale(1)"},title:"Play",children:q.jsx(ec,{size:Math.max(22,28*Be),color:"white",style:{marginLeft:"4px",filter:"drop-shadow(0 1px 3px rgba(0, 0, 0, 0.5))"}})}),F.showAds&&q.jsxs("div",{style:{position:"absolute",top:"".concat(12*Be,"px"),left:"".concat(12*Be,"px"),zIndex:20,display:"flex",alignItems:"center",gap:"8px",animation:"sc-fade-in 0.3s ease"},children:[q.jsx("div",{style:{background:"rgba(234, 179, 8, 0.9)",backdropFilter:"blur(12px)",color:"#000",padding:"".concat(4*Be,"px ").concat(12*Be,"px"),borderRadius:"6px",fontSize:"".concat(11*Be,"px"),fontWeight:"700",letterSpacing:"0.08em",textTransform:"uppercase",boxShadow:"0 2px 12px rgba(234, 179, 8, 0.3)"},children:"Ad"}),F.currentIndex>0&&q.jsxs("div",{style:{background:"rgba(0, 0, 0, 0.5)",backdropFilter:"blur(12px)",color:"rgba(255, 255, 255, 0.8)",padding:"".concat(4*Be,"px ").concat(10*Be,"px"),borderRadius:"6px",fontSize:"".concat(11*Be,"px"),fontWeight:"600",border:"1px solid rgba(255, 255, 255, 0.08)"},children:[F.currentIndex," of ",Math.max(F.totalAds,F.currentIndex)]})]}),Ke&&!Re?q.jsxs("div",{className:"sc-controls-bar",style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(0deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%)",padding:"".concat(20*Be,"px ").concat(12*Be,"px ").concat(8*Be,"px"),zIndex:10,opacity:De||F.showAds?1:0,transform:De||F.showAds?"translateY(0)":"translateY(6px)",pointerEvents:De||F.showAds?"auto":"none"},children:[q.jsxs("div",{className:"sc-progress-track",style:{width:"100%",height:"3px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"1.5px",marginBottom:"".concat(8*Be,"px"),cursor:"pointer",position:"relative",transition:"height 0.1s ease"},onClick:function(e){if(R.current&&re>0&&isFinite(re)){var t=e.currentTarget.getBoundingClientRect(),i=e.clientX-t.left,r=Math.max(0,Math.min(1,i/t.width))*re;isFinite(r)&&r>=0&&r<=re&&(R.current.currentTime=r)}Ue()},onMouseEnter:function(e){e.currentTarget.style.height="5px"},onMouseLeave:function(e){e.currentTarget.style.height="3px"},children:[q.jsx("div",{style:{position:"absolute",top:0,left:0,bottom:0,background:F.showAds?"#f5c518":"#ff0000",borderRadius:"1.5px",width:"".concat(Ye,"%"),transition:"width 0.15s linear"}}),q.jsx("div",{className:"sc-progress-thumb",style:{position:"absolute",top:"50%",left:"".concat(Ye,"%"),transform:"translate(-50%, -50%) scale(0)",width:"13px",height:"13px",background:F.showAds?"#f5c518":"#ff0000",borderRadius:"50%",boxShadow:"0 0 4px rgba(0, 0, 0, 0.3)",transition:"transform 0.1s ease, left 0.15s linear"}})]}),q.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",gap:"".concat(8*Be,"px")},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Be,"px")},children:[q.jsx("button",{className:"sc-ctrl-btn",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)}),Le(!1)):(R.current.pause(),Le(!0)));Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:$?"Pause":"Play",children:$?q.jsx(Zu,{size:Math.max(14,18*Be)}):q.jsx(ec,{size:Math.max(14,18*Be),style:{marginLeft:"2px"}})}),q.jsxs("div",{style:{display:"flex",alignItems:"center"},onMouseEnter:function(){return fe(!0)},onMouseLeave:function(){return fe(!1)},children:[q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){D.current&&D.current.toggleMute(),null==d||d(),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:H?"Unmute":"Mute",children:q.jsx(ze,{size:Math.max(14,18*Be)})}),q.jsx("div",{style:{width:he?"".concat(62*Be,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:he?"2px":"0",paddingRight:he?"4px":"0"},children:q.jsxs("div",{style:{position:"relative",width:"".concat(56*Be,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,i=function(e){var i=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-i.left)/i.width)))},r=function(){document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",r)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",r);var n=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-t.left)/t.width)))},children:[q.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(255, 255, 255, 0.2)",borderRadius:"1.5px"}}),q.jsx("div",{style:{position:"absolute",top:0,left:0,bottom:0,width:"".concat(100*(H?0:se),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(H?0:se),"%"),transform:"translate(-50%, -50%)",width:"12px",height:"12px",background:"#fff",borderRadius:"50%",boxShadow:"0 0 3px rgba(0, 0, 0, 0.3)",transition:"left 0.1s ease-out"}})]})})]}),q.jsxs("div",{style:{fontSize:"".concat(13*Be,"px"),fontFamily:"Roboto, 'Segoe UI', Arial, sans-serif",color:"rgba(255, 255, 255, 0.9)",display:xe<480?"none":"block",fontVariantNumeric:"tabular-nums",userSelect:"none",marginLeft:"".concat(4*Be,"px")},children:[Ge(ee)," ",q.jsx("span",{style:{color:"rgba(255,255,255,0.5)"},children:"/"})," ",Ge(re)]})]}),q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Be,"px")},children:[q.jsxs("div",{style:{position:"relative",display:xe<600?"none":"block"},children:[q.jsxs("button",{className:"sc-ctrl-btn",onClick:function(){me(!ge),Ue()},style:{padding:"".concat(6*Be,"px ").concat(10*Be,"px"),borderRadius:"".concat(6*Be,"px"),fontSize:"".concat(13*Be,"px"),fontFamily:"'SF Mono', 'Cascadia Code', monospace",fontWeight:"600",minHeight:"".concat(32*Be,"px")},title:"Playback Speed",children:[ue,"x"]}),ge&&q.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"8px",background:"rgba(0, 0, 0, 0.8)",backdropFilter:"blur(24px)",WebkitBackdropFilter:"blur(24px)",borderRadius:"10px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"80px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5)",animation:"sc-fade-in 0.15s ease"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(function(e){return q.jsxs("button",{onClick:function(){return t=e,R.current&&isFinite(t)&&t>0&&(R.current.playbackRate=t),void me(!1);var t},style:{display:"block",width:"100%",padding:"".concat(8*Be,"px ").concat(14*Be,"px"),background:ue===e?"rgba(255, 255, 255, 0.12)":"transparent",border:"none",color:ue===e?"#fff":"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"".concat(12*Be,"px"),fontFamily:"'SF Mono', monospace",fontWeight:ue===e?"700":"500",textAlign:"center",transition:"background 0.15s ease, color 0.15s ease"},onMouseEnter:function(t){ue!==e&&(t.target.style.background="rgba(255, 255, 255, 0.08)",t.target.style.color="#fff")},onMouseLeave:function(t){ue!==e&&(t.target.style.background="transparent",t.target.style.color="rgba(255, 255, 255, 0.7)")},children:[e,"x"]},e)})})]}),q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){h?h():M.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):M.current.requestFullscreen().catch(function(){})),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:W?"Exit Fullscreen":"Enter Fullscreen",children:W?q.jsx($u,{size:Math.max(14,18*Be)}):q.jsx(Ju,{size:Math.max(14,18*Be)})})]})]})]}):u&&!Re&&q.jsxs("div",{className:"sc-controls-bar",style:{position:"absolute",bottom:"".concat(10*Be,"px"),right:"".concat(10*Be,"px"),display:"flex",flexDirection:Fe?"column":"row",gap:"".concat(8*Be,"px"),zIndex:10,opacity:De?1:0,transform:De?"translateY(0)":"translateY(4px)",pointerEvents:De?"auto":"none"},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",background:"rgba(0, 0, 0, 0.6)",borderRadius:"".concat(18*Be,"px"),padding:"2px"},onMouseEnter:function(){return fe(!0)},onMouseLeave:function(){return fe(!1)},children:[q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){D.current&&D.current.toggleMute(),null==d||d(),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px")},title:H?"Unmute":"Mute",children:q.jsx(ze,{size:Math.max(14,18*Be)})}),q.jsx("div",{style:{width:he?"".concat(62*Be,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:he?"2px":"0",paddingRight:he?"6px":"0"},children:q.jsxs("div",{style:{position:"relative",width:"".concat(56*Be,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,i=function(e){var i=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-i.left)/i.width)))},r=function(){document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",r)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",r);var n=t.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();Ve(Math.max(0,Math.min(1,(e.clientX-t.left)/t.width)))},children:[q.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(255, 255, 255, 0.2)",borderRadius:"1.5px"}}),q.jsx("div",{style:{position:"absolute",top:0,left:0,bottom:0,width:"".concat(100*(H?0:se),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(H?0:se),"%"),transform:"translate(-50%, -50%)",width:"12px",height:"12px",background:"#fff",borderRadius:"50%",boxShadow:"0 0 3px rgba(0, 0, 0, 0.3)",transition:"left 0.1s ease-out"}})]})})]}),q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){h?h():M.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):M.current.requestFullscreen().catch(function(){})),Ue()},style:{padding:"".concat(8*Be,"px"),borderRadius:"50%",minWidth:"".concat(36*Be,"px"),minHeight:"".concat(36*Be,"px"),background:"rgba(0, 0, 0, 0.6)"},title:W?"Exit Fullscreen":"Enter Fullscreen",children:W?q.jsx($u,{size:Math.max(14,18*Be)}):q.jsx(Ju,{size:Math.max(14,18*Be)})})]}),f&&q.jsx("div",{onClick:f,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var i,r,n,a,s,o;try{for(var l=_(ac),u=l.next();!u.done;u=l.next()){if(e[v=u.value]!==t[v])return!1}}catch(e){i={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(i)throw i.error}}try{for(var 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=_(["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}),oc=function(){},lc={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:oc,onPlay:oc,onPause:oc,onBuffer:oc,onBufferEnd:oc,onEnded:oc,onError:oc,onDuration:oc,onSeek:oc,onProgress:oc,onVolumeToggle:oc,onFullscreenToggle:oc,onControlClick:oc},uc=Y.lazy,cc=function(e,t){var i=w({},e);return t.forEach(function(e){delete i[e]}),i},dc=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},hc=function(e){for(var t,i,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(!r.length)return e;var a=r.shift();if(fc(e)&&fc(a))for(var s in a)fc(a[s])?(e[s]||Object.assign(e,((t={})[s]={},t)),hc(e[s],a[s])):Object.assign(e,((i={})[s]=a[s],i));return hc.apply(void 0,M([e],x(r),!1))},fc=function(e){return e&&"object"===S(e)&&!Array.isArray(e)},vc="undefined"!=typeof window&&window.document,gc="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,mc=vc&&/iPad|iPhone|iPod/.test(navigator.userAgent),pc=vc&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),yc=/\.(m3u8)($|\?)/i,Ec=/\/hls\//i,Tc=/\.(mpd)($|\?)/i,kc=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,Sc=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,Ac={hls:function(e){return!(!e||"string"!=typeof e)&&(yc.test(e)||Ec.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&Tc.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&kc.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&Sc.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(kc.test(e)||Sc.test(e))}},bc=function(e){function t(){var t=e.apply(this,M([],x(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return D(t,void 0,void 0,function(){var e,t,i,r,n,a,s,o;return C(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 Uu(e),null===(r=(i=this.props).onMount)||void 0===r||r.call(i,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,i,r;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 i,r;console.error("[HlsPlayer] Failed to play:",e),null===(r=(i=t.props).onError)||void 0===r||r.call(i,e)}),null===(r=(i=t.props).onPlay)||void 0===r||r.call(i)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},t.pause=function(){var e,i;t.props.videoElement&&(t.props.videoElement.pause(),null===(i=(e=t.props).onPause)||void 0===i||i.call(e))},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,i){t.props.videoElement&&(t.props.videoElement.currentTime=e,i||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=Ac.hls,t}(Y.Component),Lc=function(e){function t(){var t=e.apply(this,M([],x(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,i;if(t.props.videoElement&&t.props.src){var r=t.props.videoElement,n=function(){var e,i;t.mounted&&!t.ready&&(t.ready=!0,null===(i=(e=t.props).onReady)||void 0===i||i.call(e))},a=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onPlay)||void 0===i||i.call(e))},s=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onPause)||void 0===i||i.call(e))},o=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onEnded)||void 0===i||i.call(e))},l=function(e){var i,r;t.mounted&&(null===(r=(i=t.props).onError)||void 0===r||r.call(i,e))},u=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onLoaded)||void 0===i||i.call(e))};return r.addEventListener("loadedmetadata",n),r.addEventListener("play",a),r.addEventListener("pause",s),r.addEventListener("ended",o),r.addEventListener("error",l),r.addEventListener("loadeddata",u),r.src=t.props.src,void 0!==t.props.autoplay&&(r.autoplay=t.props.autoplay),void 0!==t.props.muted&&(r.muted=t.props.muted),void 0!==t.props.loop&&(r.loop=t.props.loop),void 0!==t.props.controls&&(r.controls=t.props.controls),void 0!==t.props.playsInline&&(r.playsInline=t.props.playsInline),void 0!==t.props.preload&&(r.preload=t.props.preload),void 0!==t.props.poster&&(r.poster=t.props.poster),null===(i=(e=t.props).onMount)||void 0===i||i.call(e,t),function(){r.removeEventListener("loadedmetadata",n),r.removeEventListener("play",a),r.removeEventListener("pause",s),r.removeEventListener("ended",o),r.removeEventListener("error",l),r.removeEventListener("loadeddata",u)}}},t.play=function(){var e;if(t.props.videoElement){var i=t.props.videoElement;i.src||i.currentSrc&&""!==i.currentSrc||i.readyState>=1?null===(e=i.play())||void 0===e||e.catch(function(e){var i,r;console.error("[FilePlayer] Failed to play:",e),null===(r=(i=t.props).onError)||void 0===r||r.call(i,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,i){t.props.videoElement&&(t.props.videoElement.currentTime=e,i||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 D(t,void 0,void 0,function(){var e;return C(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 D(t,void 0,void 0,function(){var e;return C(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=Ac.file,t}(Y.Component),Ic=[{key:"hls",name:"HLS Player",canPlay:Ac.hls,lazyPlayer:uc(function(){return Promise.resolve({default:bc})})},{key:"file",name:"File Player",canPlay:Ac.file,canEnablePIP:function(e){return Ac.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:uc(function(){return Promise.resolve({default:Lc})})}],Rc=function(e){function t(){var t=e.apply(this,M([],x(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,i;if(t.props.src&&t.player&&t.isReady){var r=t.getCurrentTime()||0,n=t.getSecondsLoaded(),a=t.getDuration();if(a){var s={playedSeconds:r,played:r/a,loaded:0,loadedSeconds:0};null!==n&&(s.loadedSeconds=n,s.loaded=n/a),s.playedSeconds===t.prevPlayed&&s.loadedSeconds===t.prevLoaded||null===(i=(e=t.props).onProgress)||void 0===i||i.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,i=e.onReady,r=e.playing,n=e.volume,a=e.muted;i(),a||null===n||t.player.setVolume(n),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):r&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,i=e.onStart,r=e.onPlay,n=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==n&&t.player.setPlaybackRate(n),null==i||i(),t.startOnPlay=!1),null==r||r(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var i,r;t.isPlaying=!1,t.isLoading||null===(r=(i=t.props).onPause)||void 0===r||r.call(i,e)},t.handleEnded=function(){var e=t.props,i=e.activePlayer,r=e.loop,n=e.onEnded;i.loopOnEnded&&r&&t.seekTo(0),r||(t.isPlaying=!1,null==n||n())},t.handleError=function(){for(var e,i,r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];t.isLoading=!1,null===(i=(e=t.props).onError)||void 0===i||i.call(e,r[0],r[1],r[2],r[3])},t.handleDurationCheck=function(){var e,i;clearTimeout(t.durationCheckTimeout);var r=t.getDuration();r?t.onDurationCalled||(null===(i=(e=t.props).onDuration)||void 0===i||i.call(e,r),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 i=this.props,r=i.src,n=i.playing,a=i.volume,s=i.muted,o=i.playbackRate,l=i.loop,u=i.activePlayer;if(e.src!==r){if(this.isLoading&&!u.forceLoad&&!dc(r))return console.warn("StormcloudPlayer: the attempt to load ".concat(r," is being deferred until the player has loaded")),void(this.loadOnReady=r||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(r,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,i){var r=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,i):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,i)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){r.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=lc,t}(Y.Component),wc="undefined"!=typeof window&&window.document,Pc="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,Dc=wc||Pc?Y.Suspense:function(){return null},Cc=["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"],_c=[],xc=function(e,t){var i;return i=function(i){function r(){var r=i.apply(this,M([],x(arguments),!1))||this;return r.state={showPreview:!1},r.references={wrapper:function(e){r.wrapper=e},player:function(e){r.player=e}},r.getActivePlayer=function(i){var r,n;if(!i)return null;try{for(var a=_(M(M([],x(_c),!1),x(e),!1)),s=a.next();!s.done;s=a.next()){var o=s.value;if(o.canPlay(i))return o}}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return t||null},r.getAttributes=function(e){return cc(r.props,Cc)},r.handleReady=function(){var e,t;null===(t=(e=r.props).onReady)||void 0===t||t.call(e,r)},r.seekTo=function(e,t,i){if(!r.player)return null;r.player.seekTo(e,t,i)},r.getCurrentTime=function(){return r.player?r.player.getCurrentTime():null},r.getSecondsLoaded=function(){return r.player?r.player.getSecondsLoaded():null},r.getDuration=function(){return r.player?r.player.getDuration():null},r.getInternalPlayer=function(e){return void 0===e&&(e="player"),r.player?r.player.getInternalPlayer(e):null},r.renderActivePlayer=function(e){if(!e)return null;var t=r.getActivePlayer(e);return t?z.createElement(Rc,w(w({},r.props),{key:t.key,ref:r.references.player,activePlayer:t.lazyPlayer||t,onReady:r.handleReady})):null},r}return R(r,i),r.prototype.render=function(){var e=this.props,t=e.src,i=e.style,r=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({},i),{width:r,height:n})},o),z.createElement(Dc,{fallback:a},this.renderActivePlayer(t)))},r}(Y.Component),i.displayName="StormcloudPlayer",i.defaultProps=w(w({},lc),{fallback:null,wrapper:"div"}),i.addCustomPlayer=function(e){_c.push(e)},i.removeCustomPlayers=function(){_c.length=0},i.canPlay=function(t){var i,r;try{for(var n=_(M(M([],x(_c),!1),x(e),!1)),a=n.next();!a.done;a=n.next()){if(a.value.canPlay(t))return!0}}catch(e){i={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return!1},i.canEnablePIP=function(t){var i,r;try{for(var n=_(M(M([],x(_c),!1),x(e),!1)),a=n.next();!a.done;a=n.next()){var s=a.value;if(s.canEnablePIP&&s.canEnablePIP(t))return!0}}catch(e){i={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return!1},i},Mc=xc(Ic,Ic[Ic.length-1]);e.IS_BROWSER=vc,e.IS_GLOBAL=gc,e.IS_IOS=mc,e.IS_SAFARI=pc,e.SUPPORTS_DASH=function(){if(!vc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!vc)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=Mc,e.StormcloudVideoPlayer=Uu,e.StormcloudVideoPlayerComponent=sc,e.canPlay=Ac,e.createPrebidAdLayer=Lu,e.createPrebidManager=Eu,e.createStormcloudPlayer=xc,e.default=sc,e.detectBrowser=Ou,e.getBrowserConfigOverrides=Bu,e.getBrowserID=wu,e.getClientInfo=Ru,e.initializePolyfills=Mu,e.isMediaStream=dc,e.lazy=uc,e.logBrowserInfo=Nu,e.merge=hc,e.omit=cc,e.parseQuery=function(e){var t={},i=e.split("?")[1]||"";if(!i)return t;var r=function(e){e.split("&").forEach(function(e){var i=x(e.split("="),2),r=i[0],n=i[1];if(r)try{t[decodeURIComponent(r)]=n?decodeURIComponent(n.replace(/\+/g," ")):""}catch(e){t[r]=n||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(i).forEach(function(e,i){t[i]=e}),t}catch(e){r(i)}else r(i);return t},e.players=Ic,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.sendHeartbeat=xu,e.sendInitialTracking=Cu,e.supportsFeature=function(e){switch(e){case"ima":return Fu();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})});
|